Is there an equivalent to __attribute__((ns_returns_retained)) for a malloc'd pointer? - objective-c

I'm looking for an annotation something like
-(SomeStruct *) structFromInternals __attribute__((returns_malloced_ptr))
{
SomeStruct *ret = malloc(sizeof(SomeStruct));
//do stuff
return ret;
}
to soothe the clang static analyzer beasts.
The only viable attributes link I can find is for GCC, but it doesn't even include ns_returns_retained, which is in an extension, I assume.
EDIT:
as to why this is needed, I have a scenario that I can't repro in a simple case, so it may have to do with a c lib in an Objective-C project... The gist is, I get a static analyzer warning that the malloc in createStruct is leaked:
typedef struct{
void * data;
size_t len;
}MyStruct;
void destroyStruct(MyStruct * s)
{
if (s && s->data) {
free(s->data);
}
if (s) {
free(s);
}
}
MyStruct * createStructNoCopy(size_t len, void * data)
{
MyStruct * retStruct = malloc(sizeof(MyStruct));
retStruct->len = len;
retStruct->data = data;
return retStruct;
}
MyStruct * createStruct(size_t len, void * data)
{
char * tmpData = malloc(len);
memcpy(tmpData, data, len);
return createStructNoCopy(len, tmpData);
}
MyStruct * copyStruct(MyStruct * s)
{
return createStruct(s->len, s->data);
}

The function annotation ownership_returns(malloc) will tell the Clang static analyser that the function returns a pointer that should be passed to free() at some point (or a function with ownership_takes(malloc, ...)). For example:
void __attribute((ownership_returns(malloc))) *my_malloc(size_t);
void __attribute((ownership_takes(malloc, 1))) my_free(void *);
...
void af1() {
int *p = my_malloc(1);
return; // expected-warning{{Potential leak of memory pointed to by}}
}
void af2() {
int *p = my_malloc(1);
my_free(p);
return; // no-warning
}
(See the malloc-annotations.c test file for some more examples of their use.)
At the moment, these annotations only take effect when the alpha.unix.MallocWithAnnotations checker is run (which is not run by default). If you're using Xcode, you'll need to add -Xclang -analyzer-checker=alpha.unix.MallocWithAnnotations to your build flags.

Related

EXPECT_CALL not able to track the calls for methods called from the method under test

First of all, I'm new to Google test, so please forgive my ignorance, if any.
I'm writing unit tests using google test framework for the below class..
class MsgHandler
{
public:
MsgHandler(){}
~MsgHandler(){}
bool decode_data(unsigned char*, unsigned int,char *);
bool handle_req_state_data(char *, char *);
};
bool MsgHandler::handle_req_state_data(char *a, char *b)
{
printf("handle_req_state_data called\n");
return true;
}
bool MsgHandler::decode_data(unsigned char *a, unsigned int b,char *c)
{
printf("decode_data called\n");
handle_req_state_data(c, c);
return true;
}
As a first step, I have created the mock class as below
class MsgHandlerMock : public MsgHandler
{
public:
MsgHandlerMock()
{
}
virtual ~MsgHandlerMock() {}
MOCK_METHOD(bool, handle_req_state_data, (char *, char *), (const));
//MOCK_METHOD(int, decode_data, (unsigned char*, unsigned int ,char* ));
private:
};
Below is the test function
TEST_F(TestClass, test01)
{
MsgHandlerMock mockObj;
//EXPECT_CALL(mockObj, decode_data(::testing::_,::testing::_,::testing::_)).Times(1);
EXPECT_CALL(mockObj, handle_req_state_data(::testing::_,::testing::_)).Times(1);
mockObj.decode_data(0,0,0);
}
My intention of this test is to make sure 'handle_req_state_data' is called when I call 'decode_data' with a certain message. But my test fails with below error
decode_data called
handle_req_state_data called
...
Actual function call count doesn't match EXPECT_CALL(mockObj, handle_req_state_data(::testing::_,::testing::_))...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] TestClass.test01 (1 ms)
[----------] 1 test from TestClass (1 ms total)
Can someone help me on how to validate the inner method calls with EXPECT_CALL validators?
The function is not virtual, so can't be overridden by the mock, decode_data does not use dynamic dispatch and call the original method MsgHandler::handle_req_state_data.
virtual bool handle_req_state_data(char *, char *);
MOCK_METHOD(bool, handle_req_state_data, (char *, char *), (override));

Function not working when inside if or switch statements

I need to solve a OOP problem in which I have to manage multiple classes inherited by each other. First I need to read all the data for all the Employees of a Company. The reading runs very well but I also need to display the read data after reading the command 1 (I need to use switch). I created a function "afisare_angajati()" which only works outside "if" and "switch" statements. I don't know why those statements disable my function. This happened to me before but I couldn't find the cause. Is something that I am not seeing? You can see my function at the end of the code. Thx for help.
#include<iostream>
#include<string>
#include<vector>
class Angajat{
protected:
std::string nume;
float salariu_baza;
std::string functie;
float procent_taxe_salariu;
public:
float get_salariu_net(){return 0;}
float get_salariu_brut(){return 0;}
std::string get_nume(){return 0;}
void marire_salariu(){}
Angajat(std::string nume,float salariu_baza,std::string functie,float procent_taxe_salariu=40):
nume(nume),salariu_baza(salariu_baza),functie(functie),procent_taxe_salariu(procent_taxe_salariu){}
void display(){
std::cout<<nume<<'\n';
std::cout<<functie<<'\n';
}
};
class Analist:public Angajat{
public:
Analist(std::string nume,float salariu_baza,std::string functie,float procent_taxe_salariu=40):
Angajat(nume,salariu_baza,functie,procent_taxe_salariu){}
};
class Programator:public Analist{
protected:
float procent_deducere_salariu_it;
public:
Programator(std::string nume,float salariu_baza,std::string functie,float procent_taxe_salariu=40):
Analist(nume,salariu_baza,functie,procent_taxe_salariu){}
};
class LiderEchipaProgramare:public Programator{
protected:
int vechime;
float bonus_vechime;
public:
LiderEchipaProgramare(std::string nume,float salariu_baza,std::string functie,int vechime,float procent_taxe_salariu=40):
Programator(nume,salariu_baza,functie,procent_taxe_salariu),vechime(vechime){
bonus_vechime=500;
}
};
class FirmaProgramare{
private:
std::vector<Angajat*> vec_ang;
public:
void afisare_angajati(){
for(Angajat* a:vec_ang){
a->display();
}
}
void mareste_salarii(float,float,float){}
void promoveaza(std::string){}
void adauga_angajat(Angajat* a){
vec_ang.push_back(a);
}
};
int main(){
std::string nume;
std::string functie;
float salariu_baza;
int vechime;
int nr_ang,comanda;
FirmaProgramare pula;
std::cin>>nr_ang;
for(int i=0;i<nr_ang;++i){
std::cin.ignore();
std::getline(std::cin,nume);
std::cin>>functie;
std::cin>>salariu_baza;
Angajat* p = nullptr;
if(functie=="Analist"){
p = new Analist(nume,salariu_baza,functie);
}
else{
if(functie=="Programator"){
p = new Programator(nume,salariu_baza,functie);
}
else{
p = new LiderEchipaProgramare(nume,salariu_baza,functie,vechime);
}
}
pula.adauga_angajat(p);
}
std::cin>>comanda;
//pula.afisare_angajati(); output is correct if I put the function outside of brackets
switch(comanda)
{
case 1:{
pula.afisare_angajati();
break;
}
}
}

Infinite printing on read command of character device (through cat command) [duplicate]

I am working on simple character device driver. I have implemented read and write functions in the module, the problem is when I try to read the device file using cat /dev/devicefile it is going into infinite loop i.e. reading the same data repeatedly. Can someone suggest me any solution to this problem? Below is my driver code.
#include<linux/module.h>
#include<linux/fs.h>
#include<linux/string.h>
#include<asm/uaccess.h>
#include<linux/init.h>
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("character device driver");
MODULE_AUTHOR("Srinivas");
static char msg[100]={0};
static int t;
static int dev_open(struct inode *, struct file *);
static int dev_rls(struct inode *, struct file *);
static ssize_t dev_read(struct file *, char *,size_t, loff_t *);
static ssize_t dev_write(struct file *, const char *, size_t,loff_t *);
static struct file_operations fops =
{
.read = dev_read,
.open = dev_open,
.write = dev_write,
.release = dev_rls,
};
static int himodule( void )
{
t = 0;
t = register_chrdev(0, "chardevdriver", &fops);
if (t < 0)
printk(KERN_ALERT"device registration failed\n");
else
printk(KERN_ALERT"device registered successfully\n");
printk(KERN_ALERT"major number is %d", t);
return 0;
}
static void byemodule(void)
{
unregister_chrdev(t, "chardevdriver");
printk(KERN_ALERT"successfully unregistered\n");
}
static int dev_open(struct inode *inod, struct file *fil)
{
printk(KERN_ALERT"inside the dev open");
return 0;
}
static ssize_t dev_read(struct file *filp, char *buff, size_t len, loff_t *off)
{
short count = 0;
while (msg[count] != 0) {
put_user(msg[count], buff++);
count++;
}
return count;
}
static ssize_t dev_write(struct file *filp, const char *buff, size_t len, loff_t *off)
{
short count = 0;
printk(KERN_ALERT"inside write\n");
memset(msg,0,100);
printk(KERN_ALERT" size of len is %zd",len);
while (len > 0) {
msg[count] = buff[count];
len--;
count++;
}
return count;
}
static int dev_rls(struct inode *inod,struct file *fil)
{
printk(KERN_ALERT"device closed\n");
return 0;
}
module_init(himodule);
module_exit(byemodule);
.read function should also correctly process its len and off arguments. The simplest way to implement reading from memory-buffered file is to use simple_read_from_buffer helper:
static ssize_t dev_read(struct file *filp, char *buff, size_t len, loff_t *off)
{
return simple_read_from_buffer(buff, len, off, msg, 100);
}
You can inspect code of that helper (defined in fs/libfs.c) for educational purposes.
BTW, for your .write method you could use simple_write_to_buffer helper.
You are not respecting the buffer size passed into the dev_read function, so you may be invoking undefined behaviour in cat. Try this:
static ssize_t dev_read( struct file *filp, char *buff, size_t len, loff_t *off )
{
size_t count = 0;
printk( KERN_ALERT"inside read %d\n", *off );
while( msg[count] != 0 && count < len )
{
put_user( msg[count], buff++ );
count++;
}
return count;
}
This problem can be solved by correctly setting *off (fourth parameter of my_read()).
You need to return count for the first time and zero from second time onwards.
if(*off == 0) {
while (msg[count] != 0) {
put_user(msg[count], buff++);
count++;
(*off)++;
}
return count;
}
else
return 0;

How to get runtime Block type metadata in Objective-c?

I'm writing a class where you register an object and a property to observe. When the property gets set to something non-nil, a registered callback selector is called (like target-action). The selector may have three different signatures, and the right one is called depending on which type was registered.
This works fine, but now I want to add the ability to register a Block instead of a selector as the "callback function". Is it possible to find out the function signature of the supplied Block and handle the callback differently depending on the type of Block supplied?
For example:
- (void)registerCallbackBlock:(id)block
{
if ([self isBlock:block] {
if ([self isMethodSignatureOne:block]) { /* */ }
else if ([self isMethodSignatureTwo:block]) { /* */ }
else { assert(false); } // bad Block signature
block_ = block; // assuming ARC code
}
else { assert(false); } // not a block
}
- (void)callBlock
{
if ([self isMethodSignatureOne:block_] {
block_(arg1_, arg2_); // needs casting?
}
else if ([self isMethodSignatureTwo:block_) {
block_(arg1_, arg2_, arg3_); // needs casting?
}
}
Any ideas?
I know I can make different register functions with specific typedef'ed Block arguments but I would rather have a single function, if possible.
If you're compiling with clang, you can get this information.
From the Clang block ABI spec:
The ABI of blocks consist of their layout and the runtime functions required by the compiler.
A Block consists of a structure of the following form:
struct Block_literal_1 {
void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock
int flags;
int reserved;
void (*invoke)(void *, ...);
struct Block_descriptor_1 {
unsigned long int reserved; // NULL
unsigned long int size; // sizeof(struct Block_literal_1)
// optional helper functions
void (*copy_helper)(void *dst, void *src); // IFF (1<<25)
void (*dispose_helper)(void *src); // IFF (1<<25)
// required ABI.2010.3.16
const char *signature; // IFF (1<<30)
} *descriptor;
// imported variables
};
The following flags bits are in use thusly for a possible ABI.2010.3.16:
enum {
BLOCK_HAS_COPY_DISPOSE = (1 << 25),
BLOCK_HAS_CTOR = (1 << 26), // helpers have C++ code
BLOCK_IS_GLOBAL = (1 << 28),
BLOCK_HAS_STRET = (1 << 29), // IFF BLOCK_HAS_SIGNATURE
BLOCK_HAS_SIGNATURE = (1 << 30),
};
In practice, the current version of clang does encode signature information. According to a comment here, the format is just a standard objective-c method encoding string. That said, the signature format isn't documented (as fas as I can tell), so I'm not sure how much you can assume it won't break with compiler updates.
I don't believe this is actually possible with the current ABI. However, you could do something like this:
- (void)registerSimpleCallback: (BlockWith2Args)block {
BlockWith3Args wrapper = ^ (id arg1, id arg2, id arg3) {
block(a, b);
};
[self registerComplexCallback: wrapper];
}
- (void)registerComplexCallback: (BlockWith3Args)block {
[block_ release];
block_ = [block copy];
}
- (void)callBlock {
if (block_)
block_(arg1, arg2, arg3);
}
Yes we can, as I answered in another question.
The block struct is a published clang standard, and AFAIK, can be used all you want.

Creating a custom CFType

Is it possible to create opaque types not derived from CFTypeRef which can be retained/released with CFRetain/CFRelease? Or how do I derive a new type from a CFType?
I've never done this, but it is possible using private API. In all likelihood it will be dependent on a specific dot release of OS X, since the CF runtime could change from release to release. In any case, CF is open source so I took a look at what CFRuntime does. I was happy to see Apple included an example:
// ========================= EXAMPLE =========================
// Example: EXRange -- a "range" object, which keeps the starting
// location and length of the range. ("EX" as in "EXample").
// ---- API ----
typedef const struct __EXRange * EXRangeRef;
CFTypeID EXRangeGetTypeID(void);
EXRangeRef EXRangeCreate(CFAllocatorRef allocator, uint32_t location, uint32_t length);
uint32_t EXRangeGetLocation(EXRangeRef rangeref);
uint32_t EXRangeGetLength(EXRangeRef rangeref);
// ---- implementation ----
#include <CoreFoundation/CFBase.h>
#include <CoreFoundation/CFString.h>
struct __EXRange {
CFRuntimeBase _base;
uint32_t _location;
uint32_t _length;
};
static Boolean __EXRangeEqual(CFTypeRef cf1, CFTypeRef cf2) {
EXRangeRef rangeref1 = (EXRangeRef)cf1;
EXRangeRef rangeref2 = (EXRangeRef)cf2;
if (rangeref1->_location != rangeref2->_location) return false;
if (rangeref1->_length != rangeref2->_length) return false;
return true;
}
static CFHashCode __EXRangeHash(CFTypeRef cf) {
EXRangeRef rangeref = (EXRangeRef)cf;
return (CFHashCode)(rangeref->_location + rangeref->_length);
}
static CFStringRef __EXRangeCopyFormattingDesc(CFTypeRef cf, CFDictionaryRef formatOpts) {
EXRangeRef rangeref = (EXRangeRef)cf;
return CFStringCreateWithFormat(CFGetAllocator(rangeref), formatOpts,
CFSTR("[%u, %u)"),
rangeref->_location,
rangeref->_location + rangeref->_length);
}
static CFStringRef __EXRangeCopyDebugDesc(CFTypeRef cf) {
EXRangeRef rangeref = (EXRangeRef)cf;
return CFStringCreateWithFormat(CFGetAllocator(rangeref), NULL,
CFSTR("<EXRange %p [%p]>{loc = %u, len = %u}"),
rangeref,
CFGetAllocator(rangeref),
rangeref->_location,
rangeref->_length);
}
static void __EXRangeEXRangeFinalize(CFTypeRef cf) {
EXRangeRef rangeref = (EXRangeRef)cf;
// nothing to finalize
}
static CFTypeID _kEXRangeID = _kCFRuntimeNotATypeID;
static CFRuntimeClass _kEXRangeClass = {0};
/* Something external to this file is assumed to call this
* before the EXRange class is used.
*/
void __EXRangeClassInitialize(void) {
_kEXRangeClass.version = 0;
_kEXRangeClass.className = "EXRange";
_kEXRangeClass.init = NULL;
_kEXRangeClass.copy = NULL;
_kEXRangeClass.finalize = __EXRangeEXRangeFinalize;
_kEXRangeClass.equal = __EXRangeEqual;
_kEXRangeClass.hash = __EXRangeHash;
_kEXRangeClass.copyFormattingDesc = __EXRangeCopyFormattingDesc;
_kEXRangeClass.copyDebugDesc = __EXRangeCopyDebugDesc;
_kEXRangeID = _CFRuntimeRegisterClass((const CFRuntimeClass * const)&_kEXRangeClass);
}
CFTypeID EXRangeGetTypeID(void) {
return _kEXRangeID;
}
EXRangeRef EXRangeCreate(CFAllocatorRef allocator, uint32_t location, uint32_t length) {
struct __EXRange *newrange;
uint32_t extra = sizeof(struct __EXRange) - sizeof(CFRuntimeBase);
newrange = (struct __EXRange *)_CFRuntimeCreateInstance(allocator, _kEXRangeID, extra, NULL);
if (NULL == newrange) {
return NULL;
}
newrange->_location = location;
newrange->_length = length;
return (EXRangeRef)newrange;
}
uint32_t EXRangeGetLocation(EXRangeRef rangeref) {
return rangeref->_location;
}
uint32_t EXRangeGetLength(EXRangeRef rangeref) {
return rangeref->_length;
}
#endif
CoreFoundation itself does not provide any such mechanism, but all Cocoa objects will work with CFRetain and CFRelease. So the only supported answer is: Create a class based on Foundation and CoreFoundation will recognize it as a CFTypeRef.