How to undefine system function-like macros? - macos

I'm trying to build a code which defines a method howmany().
In OSX there is a function-like macro with the same name in /usr/include/sys/types.h
#define howmany(x, y) __DARWIN_howmany(x, y)
Following a previous question, I've tried including #undef in the header file as
#ifdef howmany
#undef howmany /*undefining '/usr/include/sys/types.h' */
#endif
But the function-like macro remains active.
/usr/include/sys/types.h:184:9: note: macro 'howmany' defined here #define howmany(x, y) __DARWIN_howmany(x, y) /* # y's == x bits? */
How should I deactivate this function-like macro?

This is incredibly fragile. Yes, you can probably get it to work, but very small changes to how things are imported will cause it to fail again (or worse, just call the wrong code). You need to make sure that #undef is included in every file that might include types.h and that it's undefined after it's defined. This is many ways it can break. Rename your function. The name is taken.

Related

Is there any difference between #define and # define? [duplicate]

I know that #defines, etc. are normally never indented. Why?
I'm working in some code at the moment which has a horrible mixture of #defines, #ifdefs, #elses, #endifs, etc. All these often mixed in with normal C code. The non-indenting of the #defines makes them hard to read. And the mixture of indented code with non-indented #defines is a nightmare.
Why are #defines typically not indented? Is there a reason one wouldn't indent (e.g. like this code below)?
#ifdef SDCC
#if DEBUGGING == 1
#if defined (pic18f2480)
#define FLASH_MEMORY_END 0x3DC0
#elif defined (pic18f2580)
#define FLASH_MEMORY_END 0x7DC0
#else
#error "Can't set up flash memory end!"
#endif
#else
#if defined (pic18f2480)
#define FLASH_MEMORY_END 0x4000
#elif defined (pic18f2580)
#define FLASH_MEMORY_END 0x8000
#else
#error "Can't set up flash memory end!"
#endif
#endif
#else
#if DEBUGGING == 1
#define FLASH_MEMORY_END 0x7DC0
#else
#define FLASH_MEMORY_END 0x8000
#endif
#endif
Pre-ANSI C preprocessor did not allow for space between the start of a line and the "#" character; the leading "#" had to always be placed in the first column.
Pre-ANSI C compilers are non-existent these days. Use which ever style (space before "#" or space between "#" and the identifier) you prefer.
http://www.delorie.com/gnu/docs/gcc/cpp_48.html
As some have already said, some Pre-ANSI compilers required the # to be the first char on the line but they didn't require de preprocessor directive to be attached to it, so indentation was made this way.
#ifdef SDCC
# if DEBUGGING == 1
# if defined (pic18f2480)
# define FLASH_MEMORY_END 0x3DC0
# elif defined (pic18f2580)
# define FLASH_MEMORY_END 0x7DC0
# else
# error "Can't set up flash memory end!"
# endif
# else
# if defined (pic18f2480)
# define FLASH_MEMORY_END 0x4000
# elif defined (pic18f2580)
# define FLASH_MEMORY_END 0x8000
# else
# error "Can't set up flash memory end!"
# endif
# endif
#else
# if DEBUGGING == 1
# define FLASH_MEMORY_END 0x7DC0
# else
# define FLASH_MEMORY_END 0x8000
# endif
#endif
I've often seen this style in old Unix headers but I hate it as the syntax coloring often fails on such code. I use a very visible color for pre-processor directive so that they stand out (they are at a meta-level so should not be part of the normal flow of code).
You can even see that SO does not color the sequence in a useful manner.
Regarding the parsing of preprocessor directives, the C99 standard (and the C89 standard before it) were clear about the sequence of operations performed logically by the compiler. In particular, I believe it means that this code:
/* */ # /* */ include /* */ <stdio.h> /* */
is equivalent to:
#include <stdio.h>
For better or worse, GCC 3.4.4 with '-std=c89 -pedantic' accepts the comment-laden line, at any rate. I'm not advocating that as a style - not for a second (it is ghastly). I just think that it is possible.
ISO/IEC 9899:1999 section 5.1.1.2 Translation phases says:
[Character mapping, including trigraphs]
[Line splicing - removing backslash newline]
The source file is decomposed into preprocessing tokens and sequences of
white-space characters (including comments). A source file shall not end in a
partial preprocessing token or in a partial comment. Each comment is replaced by
one space character. New-line characters are retained. Whether each nonempty
sequence of white-space characters other than new-line is retained or replaced by
one space character is implementation-defined.
Preprocessing directives are executed, macro invocations are expanded, [...]
Section 6.10 Preprocessing directives says:
A preprocessing directive consists of a sequence of preprocessing tokens that begins with
a # preprocessing token that (at the start of translation phase 4) is either the first character
in the source file (optionally after white space containing no new-line characters) or that
follows white space containing at least one new-line character, and is ended by the next
new-line character.
The only possible dispute is the parenthetical expression '(at the start of translation phase 4)', which could mean that the comments before the hash must be absent since they are not otherwise replaced by spaces until the end of phase 4.
As others have noted, the pre-standard C preprocessors did not behave uniformly in a number of ways, and spaces before and in preprocessor directives was one of the areas where different compilers did different things, including not recognizing preprocessor directives with spaces ahead of them.
It is noteworthy that backslash-newline removal occurs before comments are analyzed.
Consequently, you should not end // comments with a backslash.
I don't know why it's not more common. There are certainly times when I like to indent preprocessor directives.
One thing that keeps getting in my way (and sometimes convinces me to stop trying) is that many or most editors/IDEs will throw the directive to column 1 at the slightest provocation. Which is annoying as hell.
These days I believe this is mainly a choice of style. I think at one point in the distant past, not all compilers supported the notion of indenting preprocessor defines. I did some research and was unable to back up that assertion. But in any case, it appears that all modern compilers support the idea of indenting pre-processor macro. I do not have a copy of the C or C++ standard though so I do not know if this is standard behavior or not.
As to whether or not it's good style. Personally, I like the idea of keeping them all to the left. It gives you a consistent place to look for them. Yeah it can get annoying when there are very nested macros. But if you indent them, you'll eventually end up with even weirder looking code.
#if COND1
void foo() {
#if COND2
int i;
#if COND3
i = someFunction()
cout << i << eol;
#endif
#endif
}
#endif
For the example you've given it may be appropriate to use indentation to make it clearer, seeing as you have such a complex structure of nested directives.
Personally I think it is useful to keep them not indented most of the time, because these directives operate separately from the rest of your code. Directives such as #ifdef are handled by the pre-processor, before the compiler ever sees your code, so a block of code after an #ifdef directive may not even be compiled.
Keeping directives visually separated from the rest of your code is more important when they are interspersed with code (rather than a dedicated block of directives, as in the example you give).
In almost all the currently available C/CPP compilers it is not restricted. It's up to the user to decide how you want to align code.
So happy coding.
I'm working in some code at the moment which has a horrible mixture of #defines, #ifdefs, #elses, #endifs, #etc. All these often mixed in with normal C code. The non-indenting of the #defines makes them hard to read. And the mixture of indented code with non-indented #defines is a nightmare.
A common solution is to comment the directives, so that you easily know what they refer to:
#ifdef FOO
/* a lot of code */
#endif /* FOO */
#ifndef FOO
/* a lot of code */
#endif /* not FOO */
I know this is old topic but I wasted couple of days searching for solution. I agree with initial post that intending makes code cleaner if you have lots of them (in my case I use directives to enable/disable verbose logging). Finally, I found solution here which works Visual Studio 2017
If you like to indent #pragma expressions, you can enable it under: Tools > Options > Text Editor > C/C++ > Formatting > Indentation > Position of preprocessor directives > Leave indented
The only problem left is that auto code layout fixed that formatting =(

Copy constructor called on *this

I defined a copy constructor for a class A. Due to an unfortunate macro expansion, I ended up compiling the following:
A a = a;
I (eventually) realized this results in a call to A::A(const A& rhs) with this==&rhs.
Why does the compiler allow this? Conceptually I would assume that since a is declared in this statement, it wouldn't yet be available for use on the RHS.
Should I defensively check this==&rhs whenever I define a copy constructor?
I am using gcc version 5.4.0 with -std=c++11.
In a declaration, the identifier being declared is in scope as soon as it appears. There are some valid uses of this, e.g. void *p = &p;
It's normal for the copy-constructor to assume no self-copy, leaving it up to the caller to not make this mistake. Preferably, follow the rule of zero.
It would be better to not write A a = a; in the first place. To avoid this you could get in the habit of using auto, e.g.
#define F(x) auto a = A(x)
#define G(x) A a = x
Now if you write G(a); you silently get the bug, but F(a); fails to compile.

Why do some include guards have a defined value?

Usually when using include guards I write them like so:
#ifndef FILENAME_H
#define FILENAME_H
...
#endif // FILENAME_H
Now in some librarys I've seen something like:
#ifndef FILENAME_H
#define FILENAME_H 1
...
#endif // FILENAME_H
After some reserach I didn't find any reason as to why the include-gurad would be needed to be initialized.
Is there any reason for doing this?
Though I've never seen such a compiler, I've been told an "empty" define could be regarded as not defined.
I'm very interested in which compiler behaves like so.
Even C89 states:
3.8.1 Conditional inclusion
Constraints
The expression that controls conditional inclusion shall be an integral constant expression [...] of the form
defined identifier
defined ( identifier )
which evaluate to 1 if the identifier is currently defined as a macro name (that is, if it is predefined or if it has been the subject of a #define preprocessing directive without an intervening #undef directive with the same subject identifier), 0 if it is not.

register_kprobe is returning -2

I am trying to hook some kernel function for learning purpose, I wrote the simple kernel module below, but for some reasons, the register_kprobe always returns -2. I didn't find nothing about what it says what this error means and have no idea how to continue. At first I thought it is because list_add is an inline function, so I tried replacing it with kvm_create_vm and got the same result. Then I checked the /proc/kallsyms and found that both don't appear there. So I chose kvm_alloc which is exported, and still I get error -2. I also tried alloc_uid but this worked just fine.
My question: What kind of functions can be hooked with kprobes?
#undef __KERNEL__
#define __KERNEL__
#undef MODULE
#define MODULE
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/ptrace.h>
MODULE_LICENSE("GPL");
static int pre(struct kprobe *kp, struct pt_regs *regs){
printk(KERN_INFO "It is working!\n");
return 0;
}
static struct kprobe kp = {
.symbol_name = "list_add",
.pre_handler = pre,
.post_handler = NULL,
.fault_handler = NULL
};
int init_module(void){
printk(KERN_INFO "Hi\n");
printk(KERN_INFO "register_kprobe: %d\n" , register_kprobe(&kp));
return 0;
}
void cleanup_module(void){
unregister_kprobe(&kp);
printk(KERN_INFO "Bye\n");
}
Edit
The line I stroked through was the main reason I got confused. I miss spelled kvm_alloc, it should be kvmalloc without the underscore. And this function got hooked just fine.
To probe inlined functions, you need to find all the PC addresses at which their inlined instances live, and plop those addresses into the struct kprobes .addr field. A tool such as systemtap searches DWARF debuginfo for such inlined functions to compute PC addresses. See readelf -w vmlinux; DW_TAG_inlined_subroutine, DW_AT_low_pc etc.
A negative return value can usually be interpreted as a negated errno value. Have a look at http://www.virtsync.com/c-error-codes-include-errno or so:
#define ENOENT 2 /* No such file or directory */
So the problem seems to be that register_kprobe could not find something, probably the list_add symbol. Let's dig into the source to figure out why it is that way.
register_kprobe calls kprobe_addr to resolve the symbol name, which in turn calls kprobe_lookup_name, which is a #define for kallsyms_lookup_name. So it seems that you need to get the symbol you want to hook into kallsyms for this to work.
For documentation about kprobes, have a look at Documentation/kprobes.txt in the kernel source tree. About kprobe'ing inline functions, it says:
If you install a probe in an inline-able function, Kprobes makes
no attempt to chase down all inline instances of the function and
install probes there. gcc may inline a function without being asked,
so keep this in mind if you're not seeing the probe hits you expect.
So, it doesn't really work for inlined functions.
Now that we have figured out the problems, let's look for solutions. You'll probably need to recompile your kernel for this though.
First, make sure that the kernel configuration option CONFIG_KALLSYMS_ALL is turned on – that makes sure that kallsyms knows about more symbols. Then, try moving the implementation of list_add into a seperate .c file and adding __attribute__ ((noinline)) to it. That new kernel build is going to be slower, but I think that your kprobe module should work with it.

How define macro as _Pragma with macro argument

I have been writing C++ for a while but have very little macro experience. I have read some of the other questions on this topic but I just can't quite translate them to my problem.
I want to define a macro such that coding ENUM_PRAGMA(foo) produces _Pragma("enum(foo)") which I intend to have the effect of #pragma enum(foo)
(The compiler supports _Pragma("string").)
I have tried multiple variations of
#define ENUM_PRAGMA(siz) \
_Pragma( "enum(" #siz ")" )
but can't get any of them to work.
Based on How do I implement a macro that creates a quoted string for _Pragma? I tried
#define HELPER1(x) enum( x )
#define HELPER2(y) HELPER1(#y)
#define ENUM_PRAGMA(siz) _Pragma(HELPER2(siz))
but I'm still not quite there. (Error is string literal was expected but enum was found so I guess my HELPER2 is not quoting the string.
Can anyone please humor me on this? Thanks much.
Okay, I got it.
I defined a general purpose macro STRINGIFY:
#define STRINGIFY(str) #str
Now the real macro comes down simply to
#define ENUM_PRAGMA(siz) _Pragma(STRINGIFY(enum(siz)))
Thanks for your patience.

Resources