Use of spinlock_check() function - c

I have a question about the function spinlock_check() used in spin_lock_init() macro.
The code of spinlock_check is written below and it returns address of rlock
static __always_inline raw_spinlock_t *spinlock_check(spinlock_t *lock)
{
return &lock->rlock;
}
It is used in the macro spin_lock_init. The code of this macro:
#define spin_lock_init(_lock) \
do { \
spinlock_check(_lock); \
raw_spin_lock_init(&(_lock)->rlock); \
} while (0)
I saw a question about this topic in here.
But i did not quite understand and I want to express doubts in my way.
The spin_lock_init() is a macro but spinlock_check() isnt a macro. Its an inline function. So I think there is no way for some compilation magic to happen here but I expect some magic during execution of those instructions.
What effect does spinlock_check() has?
Because nothing is using the return value of spinlock_check() function.
Even though spinlock_check() return something the next step is going to get executed anyways.
Because I saw its usage in one of the file and I thought that its different from min(x, y) macro.
Here is the usage which I found
#ifdef CONFIG_NUMA
static void do_numa_crng_init(struct work_struct *work)
{
int i;
struct crng_state *crng;
struct crng_state **pool;
pool = kcalloc(nr_node_ids, sizeof(*pool), GFP_KERNEL|__GFP_NOFAIL);
for_each_online_node(i) {
crng = kmalloc_node(sizeof(struct crng_state),
GFP_KERNEL | __GFP_NOFAIL, i);
spin_lock_init(&crng->lock);
crng_initialize(crng);
pool[i] = crng;
}
mb();
if (cmpxchg(&crng_node_pool, NULL, pool)) {
for_each_node(i)
kfree(pool[i]);
kfree(pool);
}
}
So here crng is dynamically allocated one. say I have missed the kmalloc code meaning I haven't allocated memory for crng but still I used the macro spin_lock_init(crng).
Now what good the spinlock_check() function does ?
Isn't it that after spinlock_check() function raw_spin_lock_init automatically executes ?
If it is going to execute then whats the use of spinlock_check() function?
There should be some meaning but I can't figure it out.

What you are missing is that spinlock_check() does not perform any check at run time. That's why its returned value is ignored. This instruction is expected to be removed during compilation by the optimizer.
Is it of any use, then? Yes! It's purpose is to ensure at compile time that the type of its parameter is spinlock_t *. If you don't give a pointer to spinlock_t as a parameter to spin_lock_init(), you will trigger a compilation error.

Related

Pointer decryption function not working as intended

First of all, it is important to say that the code will be a mess, I know that and there is a reason behind the messy code, but I prefer not to specify why to avoid going off track.
This snippet of code decrypts a pointer:
//LLUNGO is long long
//PLLUNGO is long long pointer
//SCANVELOCE is __fastcall
LLUNGO SCANVELOCE DecryptPointer(PPTR_SECRET _pSecret, PLLUNGO _OldPointer)
{
_OldPointer = (PLLUNGO) PTR_ENCRYPTION_ALGORITHM(*_OldPointer, _pSecret->Segreto);
INTERO Reference = GetReferenceToPtr(_pSecret, _OldPointer);
if (PTR_BAD_REFERENCE(Reference))
QUICK_PRINT("Bad reference error.\n");
return PTR_ENCRYPTION_ALGORITHM((LLUNGO)_pSecret->Riferimenti[Reference], _pSecret->Segreto);
}
using the following macros:
#define PTR_ENCRYPTION_ALGORITHM(PTR, KEY) (~(PTR ^ KEY))
#define PTR_BAD_REFERENCE(PTR) ((-1) == (PTR))
Now the problem is when I use the macro stated below, for some reason even if I am using the right arguments it is still throwing me this error:
no instance of overloaded function "DecryptPointer" corresponds to the
arguments.
Consider that NBYTE is BYTE and REGISTRA is the register keyword.
NBYTE SCANVELOCE MFINIT(LLUNGO _FuncAddr, PMUTILATE_FUNCTION _Function)
{
if (!_FuncAddr || !_Function)
return FALSO;
SELF_PTR_DECRYPTION( _FuncAddr ); //error thrown here
SELF_PTR_DECRYPTION( _Function ); //and here too!
for (REGISTRA PNBYTE Current = (PNBYTE)_FuncAddr; ; Current--)
{
if (MF_PUSH_EBP == *Current)
{
_Function->Inizio = (LLUNGO)Current;
break;
}
}
And the SELF_PTR_DECRYPTION macro + everything else necessary for the DecryptPointer function to work:
(PTR_SECRET being a struct)
#define SELF_PTR_DECRYPTION(X) ((X) = (PTR_DECRYPTION(X)))
#define PTR_DECRYPTION(X) DecryptPointer(&PTR_SECRET_NAME, X)
#define PTR_SECRET_NAME g_PTR_SECRET
INIT(PTR_SECRET PTR_SECRET_NAME);
Again sorry for the stupidly messy code, I'm struggling too, just like everyone reading this probably will, but again there is a reason behind the mess.
The solution has been found in the comments by #yano:
you've taken me straight to macro hell. If I'm following correctly,
_FuncAddr in the SELF_PTR_DECRYPTION( _FuncAddr ); call ends up being the 2nd argument to DecryptPointer, which expects a PLLUNGO type.
However, _FuncAddr is a LLUNGO type. And if its complaining about "no
overloaded function" it sounds like you're using a C++ compiler, not
C.
Many thanks, and sorry for the absolute mess of code I presented here.

How to define block of code inside if condition

I work with old C project and should make there several changes
It has lots of macros....
The function calls are defined there as
#define myFunc(arg) myBaseFunc(arg)
bool myBaseFunc is a function, actually there are several myBaseFunc
(its a kind of polymorphism)
I need to add some check of arguments correctness to myFunc
Actually the project has :
#define checkArg(arg) {\
// lot of code
}
I can`t change checkArg implementation
1) I thought to //
/*It is not correct if I do `if(myFunc(arg))`*/
#define myFunc(arg)\
checkArg(arg)\
myBaseFunc(arg)
2)I thought to
/*It is better...but compiler doesn`t like code block `{}` inside`if(myFunc(arg))`*/
#define myFunc(arg)(\
checkArg(arg),\
myBaseFunc(arg))
Is there a workaround for this case
A possible solution is to check the arg before it is passed to the base function. That works however only if there's only a single argument.
#define myFunc(arg) myBaseFunc(checkArg(arg))
Your checkArg function(s) must be changed so that they return the same value they got as parameter, e.g.
int checkArg(int value) {
... test stuff
return value;
}
I think It is possible like this, but you need to know argument type:
int main_check_function(void* data) { // <= this type need to be type of functions.
checkArg(data);
return (myBaseFunc(data));
}
#define myFunc(arg) (main_check_function(arg))
Although as I told, it is limited to knowing type. I just added a function to project to check your code by running checkArg() and then running myBaseFunc(). This approach is simple, but it has that big drawback.

Practical differences between "do {...} while (0)" and "{...} ((void)0)" in macros?

It's common practice in C to use:
#define FOO() do { /* body */ } while (0)
While this is fine, it's also possible to do:
#define FOO() { /* body */ }((void)0)
{...}((void)0) has many of the same benefits: you can't accidentally merge logic, and a ; is required at the end of the line, so odd expressions like this don't go by un-noticed: FOO() else {...}.
The only difference I've noticed is it means you need to use braces in if-statements.
if (a)
FOO();
else
BAR();
Must be written as:
if (a) {
FOO();
} else {
BAR();
}
Other then this quirk, it seems to work well, preventing the same kinds of problems do/while method is typically used for.
Are there any significant differences between the 2 methods?
Said differently, if you see a code-base using {...}((void)0), are practical reasons to switch to using do{..}while(0), besides the one difference already noted?
The practical difference is exactly what you pointed out.
The do { ... } while (0) idiom means that the macro can be used in any context that requires a statement.
Your suggested idiom { ... } ((void)0) can be used safely in most contexts that require an expression -- but it can fail if it's used in an unbraced if statement.
I can think of no good reason to use an unfamiliar idiom that almost always works, when there's a well known idiom that always works.
One difference is you can use break with #define FOO() do { /* body */ } while (0) but not with #define FOO() { /* body */ }(void)0.
Let's say you are inside a function, say hello(), and doing something in #define FOO() do { /*some device operation */ } while (0) but some error occurred so you no longer want to proceed with that device but there are other statements in function hello() you want to execute, let's say for another device.
So if you use second statement then you will do return most probably which will exit out of hello() but if you use the first statement you can happily break and do some operation in same function hello() for another device.

Evaluate macro parameter once only

In the following code, whatever is passed as retval is evaluated as given for every use of that token.
#define _CPFS_RETURN(commit, retval) do { \
util_cpfs_exit(commit); \
return retval; \
} while (false)
#define CPFS_RETURN_BOOL(retval) do { \
_CPFS_RETURN(retval, retval); \
} while (false)
For example given the use CPFS_RETURN_BOOL(inode && file_truncate(inode, len));, this is generated:
do {
do {
util_cpfs_exit(inode && file_truncate(inode, len));
return inode && file_truncate(inode, len);
} while (0);
} while (0);
Evidently I don't want to execute the statement inode && file_truncate(inode, len); more than once.
How can I ensure that the given tokens are evaluated before being pasted helter-skelter?
Update
I believe I have good reason to use macros here. Where possible, code is put into real functions (such as util_cpfs_exit) which are invoked from a set of macros I'm using. The macros vary based on the return type: in C++ I'd have explicit templates to handle this.
As your macro vary on the return type, you can evaluate the retval expression and store it in a variable of the right type inside the first level of macro then use this variable. ie:
#define CPFS_RETURN_BOOL(retval) do { \
bool _tmp_ = retval;
_CPFS_RETURN(_tmp_, _tmp_); \
} while (false);
If I understand well, that should be enough for your use case, and for other use cases you can use functions.
In your exemple you'll get:
do {
bool _tmp_ = inode && file_truncate(inode, len);
do {
util_cpfs_exit(_tmp_);
return _tmp_;
} while (0);
} while (0);
Looks fine.
PS: as a sidenote if you always use _CPFS_RETURN indirectly through another macro following the above model, there is no need to protect it by a do { } while (false);. Also, putting a semi-colon after the while(false) removes most of the interest of using it... that may be a good example of why C macros are dangerous and hides easy pitfalls. Not that I dislike macros, quite the contrary. I'm from the (probably rare) kind of people that would prefer C macros to be enhanced to bypass their current limitations to become really cool (and no, C++ templates are not enhanced macros, they are something completely different).
I would recommend that you evaluate the condition first.
i.e.
bool val = inode && file_truncate(inode, len);
Other than that may advice would be to steer well clear of macros, they seem unnecessary in this instance, use functions instead.
Write a function instead of using a macro. In this case, where you want to build a return statement in, you might be better off just writing the code explicitly instead of relying on a macro to hide what you're doing.
Change the macro to a "static inline" function. In gcc, it's as fast as a macro.
http://gcc.gnu.org/onlinedocs/gcc/Inline.html

Scope Guard in C

I would like to use scope guard in C in order to do profiling.
I would like to know how much time I spend in a function. Here is what I do:
int function() {
tic();
... do stuff ...
if (something)
{
toc();
return 0;
}
toc();
return 1;
}
I need to place a toc statement each time I exit the function. I would like to do that without having to copy paste toc everywhere. Is there a generic way to do that, using a macro or something ?
Also I don't want to change the way the function is called, as there are many functions I have to profile.
Thanks
This doesn't change the way the function is called. Probably not much use if you want to be able to profile every single function, though.
static inline int real_function() {
// previous contents of function(), with no tic or toc
}
int function() {
tic();
int r = real_function();
toc();
return r;
}
As everyone else says: use a profiler, it will save you a lot of effort in the long run. As they don't say: if your platform has one.
If it doesn't, then the easiest might be to say (as a coding rule) that functions must have only one exit point, and that exit point must be via your macro. Then you can manually instrument all your functions with code at entry and exit. Legacy functions with multiple returns can be wrapped up as above.
Also, bear in mind when you're doing anything like this that your compiler can mess you up. You might write this:
tic();
do_something();
int i = something_else();
toc();
return i;
If the compiler determines that something_else has no side-effects, then even though something_else takes significant time, it might turn the code into this:
tic();
do_something();
toc();
return something_else();
And your profile data will under-estimate the time spent in your function. Another reason it's so good to have a real profiler - it can co-operate with the compiler.
You could define a macro like:
#define TOC_RETURN(x) \
do { \
toc(); \
return x; \
} while(0)
which should work anywhere you put it. Then you can automate replacing return *; with TOC_RETURN(*).
Why not use an actual profiling tool, like gprof?
You could just "redefine" return via a macro: (please see Disclaimer)
#include <stdio.h>
void tic() { printf("tic\n"); }
void toc() { printf("toc\n"; }
#define return toc(); return
int foo() {
tic();
return 0;
}
#undef return
int main() {
foo();
return 0;
}
Disclaimer: This can be considered ugly and hacky because:
It won't work for void functions unless you use return;-statements.
It might not be portable/standard, even though it works on MSVC8.
One shouldn't define keywords.
I am very late to the party, but there is another way to do scope guarding in C using the GCC extension cleanup attribute. The cleanup attribute attaches a function to a variable declaration that is run when the variable goes out of scope. Originally intended to perform memory deallocation for dynamically allocated types, it can also be abused as a scope guard.
void cleanup_toc(int *ignored __attribute__((__unused__))) { toc(); }
int function(void) {
tic();
int atexit __attribute__((__cleanup__(cleanup_toc))) = 0;
//... do stuff ...
if (something) {
return 0;
}
return 1;
}
This solution does not use macros, but you can of course wrap this into a macro. For example:
#define CONCATENATE_IMPL(x, y) x ## y
#define CONCATENATE(x, y) CONCATENATE_IMPL(x, y)
#define ATEXIT(f) int CONCATENATE(atexit, __LINE__) __attribute__((__cleanup__(f))) = 0
int function(void) {
ATEXIT(cleanup1); // These are executed in reverse order, i.e.
ATEXIT(cleanup2); // cleanup2 will run before cleanup1.
}
I wouldn't recommend a macro for this. You profile the code just once in a while, and replacing 'return' with some special macro just for that purpose makes code less readable.
Isn't it better to do as follows?
tic();
call_function();
toc();
This automatically handles "all exit points" from the function.
P.S. Why don't you use a profiler?
A real profiler doesn't need you to modify the code, just to compile it with profiling enabled.
Hmm, maybe wrap the function call in a macro (family of macros, really)? Here is one which takes no arguments and returns Retval:
// define the wrapper for name
#define DEFTIMECALL0(Retval,name) \
Retval timed##name() \
{ \
Retval ret;
tic(); \
ret = name(); \
toc(); \
return ret; \
}
You'll need macros for every arity of function calls you make, with a Retval and void returning version.
Edit Maybe there isn't even a point in defining the wrapper function, and better to just have a family of macros (again, for each arity and return type/void versions) which wrap a function call in a tic/toc directly at the callsites
Don't be afraid of instrumenting profilers, which essentially do this for you.

Resources