Get line number of called function C - c

Is there a way to get the line number a function was called on in C without doing anything like below?
The define can make it tedious after a while, having to use DP instead of { like usual, and hard to read; but the adding LINE as the first parameter to every function is just something I'm not willing to do.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#define println(x,...) printf(x,##__VA_ARGS__);printf("\n");
/*
*I would like to be able to replace __LINE__ with the line
*each function was called on, or replace my DP define completely...
*/
#ifdef _DEBUG_
#define DP { println("%s:%d\t%s()",__FILE__,__LINE__,__FUNCTION__);
#else
#define DP {
#endif
void calledFunc()
DP
println("something something something");
}
void cFunc(int line)
{
println("%s:%d\t%s()",__FILE__,line,__FUNCTION__);
}
int main()
DP
calledFunc();
/* ...and I don't want to have to do this all the time either*/
cFunc(__LINE__);
}

There is a good substitute for printing the line file name/number. It is called "LocationID" or LID.
LID is a number that is generated out the project wide counter. The latest value of the counter should be stored in the source file and checked in/out of the source control system like any other source file. The value of the counter can be scrambled. This forces its proper use. You use it like:
#ifdef _DEBUG_
#define DP(x, msg) println("%d: %s", x, msg);
#endif
and in your source:
DP (3517, "Here we are.")
Advantage of the LIDs are:
They are stable against modification of the source file, including renaming of the file/function.
They are easy to find in the sources.
Log file is much more compact and clear than with the file name and the function name.
I used this several times and it proved to be good. Generation and distribution of LID values among developers is an overhead, but the result is 10 times worth the price of this effort.

Related

C89 computed goto (again) how to

I need to code an automata, and I bumped into this old need of a computed goto (ala fortran4 :) )
I need to code this in a portable ansi-C.
I want to stay away from the "don't do that", away from longjmp/setjmp, away from embedded ASM(), away from non ansi-C extensions.
Does anyone know how to do this?
Like I said in a comment, despite your plea to not use anything other than goto, standard C has nothing to offer.
Design your state appropriately, and pass a pointer to it to the handler functions for them to modify. That way the handler can setup the next function to call. Something like this:
struct state;
typedef void state_func(struct state*);
#define NULL_ACTION_ADDRESS (state_func*)0
struct state {
state_func *action;
int value1;
int value2;
};
#define INIT_STATE { initial_action, -1, -1}
state_func initial_action;
state_func handle_a;
state_func handle_b;
int main(void) {
struct state s = INIT_STATE;
while(s.action != NULL_ACTION_ADDRESS) {
(*s.action)(&s);
}
return 0;
}
void initial_action(struct state* ps) {
ps->action = &handle_a;
}
void handle_a(struct state* ps) {
ps->action = &handle_b;
}
void handle_b(struct state* ps) {
ps->action = NULL_ACTION_ADDRESS;
}
I think I got it, I reviewed all the various threads on this topics and I started to agree that that there where no ansi C solutions, yet I found an way to do this that fit my needs. All solution I saw on stackoverflow where based on the idea to 'get' the addr of a label, then stuff it into a table, then index this table and goto, this is both with gcc/clang non ansi extension or the asm extension.
I gave it another try tonite and got this.
In an include file named cgoto.h I have this
#ifndef CGOTO_dcl
#define CGOTO_dcl(N) int CGOTO_##N
#define CGOTO_LE(l) l,
#define CGOTO_LG(l) case l:goto l;
#define CGOTO_def(N) \
if(0){typedef enum {N(CGOTO_LE)} N; CGOTO_##N: switch(CGOTO_##N)\
{N(CGOTO_LG) default:CGOTO_##N=0;goto CGOTO_##N;}}
#define CGOTO(N,i) CGOTO_##N=i; goto CGOTO_##N;
#endif
The usage is like this
#include <stdio.h>
#include "cgoto.h"
int f(int x)
{ //...
CGOTO_dcl(gtb);
//...
# define gtb(L) L(l0) L(l1) L(l2)
CGOTO_def(gtb);
//...
CGOTO(gtb,x);
l0: printf("error\n");
return(0);
//...
l1:return(11);
l2:return(22);
l3:return(33);
}
int main()
{ printf("f(0)=%d f(1)=%d f(2)=%d,f(3)=%d\n",f(0),f(1),f(2),f(3));
}
In this implementation, the cost of jumping is 2 jumps and a switch() that is sequential, then optimisable. So this is reasonably performing compared to function call, a little less performing than &&label solution at the cost of portability.
With this implementation, labels code (semantic actions) are not confined into a switch() so we can implement jump table with shared semantic actions.
The index is assigned to a local goto_table_index, making the function using this re-entrant (multi threadable), though the optimiser can remove altogether this temp assignment.
The 1st Label in a jump table is 'special' (on this implementation) in the sense that it catch index out of bound, the first label is the 'error' label. If your code is bullet proof, i.e there is no way you can get an out of bound index, then the 1st label has not particular semantic.
CGOTO_dcl(gtb);
Declare the jump table 'gtb' own index as an auto integer so reentrant.
# define gtb(L) L(l0) L(l1) L(l2)
CGOTO_def(gtb);
Define a jump table named gtb, labels can be entered/removed with L(label) so it is pretty convenient, and this is symbolic by nature, i.e the labels are name with a meaning. With #define as a switch() case, labels addition/suppression often mean #define renumbering that is a problem.
The #define can be separated from the CGOTO_def() but it make more sense to keep them together. The CGOTO_def() though got to be placed after the function local declaration as it contain a switch() that is code.
A uniq jump table can be used in multiple place in the function.
CGOTO(gtb,x);
...
CGOTO(gtb,y);
A label may be entered in multiple jump table
# define gtb1(L) L(l0) L(l1) L(l2)
CGOTO_def(gtb1);
# define gtb2(L) L(l0) L(l4) L(l5)
CGOTO_def(gtb2);
So all in all, this may looks ugly, yet, the jump table definition though 2 line the #define and the CGOTO_def() is manageable and practical, semi performant, and portable.
We are back to FTN4 :)
Cheers,
Phi

Macro that resolves to first N characters of argument

I am working on a heavily resource-constrained embedded platform.
I want a macro that will capture function call errors and log them to a fixed-size buffer.
My wish is to be able to do something like
returnType retval;
CAPTURE_ERRORS(retval, function_name, argument1, moreArgsMaybe);
if (retval) { other_error_handling(); }
Where
#define N 12
#define CAPTURE_ERRORS(retval, func, ...) \
do { retval = func(__VA_ARGS__); \
if (retval!=0) write_log_entry(#func[0:N],(int)retval); \
} while (0)
Obviously, the Python slice syntax won't work. Is there any way to get the first N characters of a stringized macro argument?
(I don't want to do the truncation inside write_log_entry, because then the whole long function name will be stored in the executable image, only to be thrown away later.)
I am not aware of any way as a string. (Somebody who is aware, please enlighten me!)
Edit The easiest way I know is to make all your function names no more than N characters long! Think of all that Fortran code with N=6. :)
The second easiest way I know is to pass an additional parameter to CAPTURE_ERRORS:
#define N 12
/* vvvv */
#define CAPTURE_ERRORS(retval, func, tag, ...) \
do { retval = func(__VA_ARGS__); \
if (!retval) write_log_entry(#tag,(int)retval); \
} while (0) /* ^^^^ */
and
CAPTURE_ERRORS(retval, function_name, function_nam, argument1, moreArgsMaybe);
^^^^^^^^^^^^
This is a sufficiently restricted form that you could automatically stuff tag in your existing CAPTURE_ERRORS call with a Python (or even sed!) script that you run before compiling.
Edit
A discussion thread coming to the same conclusion — use an external tool.
In C++, you could likely do this at compile time with a template. :) Not unlike this question, but stopping at length N.

Print variable names of #define from a header file

A 3rd party library have a list of defined status variables in a header
// <status.h> -- 3rd party header file
#define SUCCESS 0
#define FAILURE 1
#define OUT_OF_MEM 2
// ... and a lot of them ...
// Functions that return the above status
int Send();
I want to display the status names, i.e. those defined variable names
// "main.c"
#include <status.h>
#include <stdio.h>
void printstat(stat)
{ // Print out stat with variable name
// Example if 0, print "SUCCESS", and so on...
}
void main()
{
int stat = Send();
printstat(stat);
}
Because too much define status variables, so what is the easy way to do that?
There is no "direct" solution. After preprocessing phase of translation unit those names are simply gone (i.e. replaced with their values). The simplest way would be to create addition array of string literals, where index of each element corresponds to macro's value. For example:
const char *status_name[] = {"SUCCESS", "FAILURE", "OUT_OF_MEM"};
The best place to place such array is header file itself. Note that you need to synchronize header with array. If it changes frequently, then you possibly need some sort of auto-generation.

How can I store C structures in human-readable files using the fewest lines of code?

I have a daemon for a scientific instrument that needs to persist about 100 unique variables. Currently, these settings are stored in binary form at explicit addresses, and each is accessed with a unique getter and setter. This is completely unmaintainable. I'd like to group settings together in sensible structures and persist those structures into files. I'll also have default values in case of incomplete files. What library or technique will allow me to save and restore these structures with as few lines of code as possible?
The fastest/easiest way to serialize a C struct is to use X-macros. This lets you define related properties together and re-use elements. This example does not do any of the error checking that should be done but with an implementation less than 30 lines it will be hard to find a shorter one. More elaborate uses are possible like automatically creating getters and setters.
#include <stdio.h>
#define SETTINGS_TABLE \
X(float, "%f", foo, 2.71818) \
X(float, "%f", bar, 0.70711) \
X(int, "%i", baz, 42)
#define X(type, fmt, name, default) type name ;
struct Settings { SETTINGS_TABLE };
#undef X
#define X(type, fmt, name, default) default ,
struct Settings settings = { SETTINGS_TABLE };
#undef X
void dump(FILE *f)
{
#define X(type, fmt, name, default) fprintf(f, "%s=" fmt "\n", #name, settings.name);
SETTINGS_TABLE
#undef X
}
void load(FILE *f)
{
#define X(type, fmt, name, default) fscanf(f, #name "=" fmt, &settings.name);
SETTINGS_TABLE
#undef X
}
int main(int argc, char *argv[])
{
FILE *cfg;
cfg = fopen(argv[1], "r");
load(cfg);
fclose(cfg);
dump(stdout);
return 0;
}
You can't simply serialize them using a library if you want human-readable files. You need to write a function which, given a filename and the structures, will write the contents of the structures in the file.I'd suggest you use a one line = one member basis, but write the name of the member too, so that you'll find which members are missing, this way: name:value.
Then, another function will need to retrieve a structure from the file. Instead of writing your own format, you could use JSON with the jansson library. **EDIT: As the comments said, libjson is another alternative, usable both in C and C++.
"Shortest" have several meanings
fast to process
eating as little as memory as possible
easy and quick to code
I would suggest to use a simple textual format to serialize them, probably JSON (or maybe YAML or XML). The advantage of such formats is that they remain somehow human "readable" (at last for a programmer).
There exist a lot of JSON libraries (notably in C and C++): jansson in C, jsoncpp for C++, etc etc...
Does your scientific instrument runs only a tiny 8 bit controller? If yes, you might be constrained by code size...
And I suggest also to document the serialized format.

get function address from name [.debug_info ??]

I was trying to write a small debug utility and for this I need to get the function/global variable address given its name. This is built-in debug utility, which means that the debug utility will run from within the code to be debugged or in plain words I cannot parse the executable file.
Now is there a well-known way to do that ? The plan I have is to make the .debug_* sections to to be loaded into to memory [which I plan to do by a cheap trick like this in ld script]
.data {
*(.data)
__sym_start = .;
(debug_);
__sym_end = .;
}
Now I have to parse the section to get the information I need, but I am not sure this is doable or is there issues with this - this is all just theory. But it also seems like too much of work :-) is there a simple way. Or if someone can tell upfront why my scheme will not work, it ill also be helpful.
Thanks in Advance,
Alex.
If you are running under a system with dlopen(3) and dlsym(3) (like Linux) you should be able to:
char thing_string[] = "thing_you_want_to_look_up";
void * handle = dlopen(NULL, RTLD_LAZY | RTLD_NOLOAD);
// you could do RTLD_NOW as well. shouldn't matter
if (!handle) {
fprintf(stderr, "Dynamic linking on main module : %s\n", dlerror() );
exit(1);
}
void * addr = dlsym(handle, thing_string);
fprintf(stderr, "%s is at %p\n", thing_string, addr);
I don't know the best way to do this for other systems, and this probably won't work for static variables and functions. C++ symbol names will be mangled, if you are interested in working with them.
To expand this to work for shared libraries you could probably get the names of the currently loaded libraries from /proc/self/maps and then pass the library file names into dlopen, though this could fail if the library has been renamed or deleted.
There are probably several other much better ways to go about this.
edit without using dlopen
/* name_addr.h */
struct name_addr {
const char * sym_name;
const void * sym_addr;
};
typedef struct name_addr name_addr_t;
void * sym_lookup(cost char * name);
extern const name_addr_t name_addr_table;
extern const unsigned name_addr_table_size;
/* name_addr_table.c */
#include "name_addr.h"
#define PREMEMBER( X ) extern const void * X
#define REMEMBER( X ) { .sym_name = #X , .sym_addr = (void *) X }
PREMEMBER(strcmp);
PREMEMBER(printf);
PREMEMBER(main);
PREMEMBER(memcmp);
PREMEMBER(bsearch);
PREMEMBER(sym_lookup);
/* ... */
const name_addr_t name_addr_table[] =
{
/* You could do a #include here that included the list, which would allow you
* to have an empty list by default without regenerating the entire file, as
* long as your compiler only warns about missing include targets.
*/
REMEMBER(strcmp),
REMEMBER(printf),
REMEMBER(main),
REMEMBER(memcmp),
REMEMBER(bsearch),
REMEMBER(sym_lookup);
/* ... */
};
const unsigned name_addr_table_size = sizeof(name_addr_table)/sizeof(name_addr_t);
/* name_addr_code.c */
#include "name_addr.h"
#include <string.h>
void * sym_lookup(cost char * name) {
unsigned to_go = name_addr_table_size;
const name_addr_t *na = name_addr_table;
while(to_to) {
if ( !strcmp(name, na->sym_name) ) {
return na->sym_addr;
}
na++;
to_do--;
}
/* set errno here if you are using errno */
return NULL; /* Or some other illegal value */
}
If you do it this way the linker will take care of filling in the addresses for you after everything has been laid out. If you include header files for all of the symbols that you are listing in your table then you will not get warnings when you compile the table file, but it will be much easier just to have them all be extern void * and let the compiler warn you about all of them (which it probably will, but not necessarily).
You will also probably want to sort your symbols by name such that you can use a binary search of the list rather than iterate through it.
You should note that if you have members in the table which are not otherwise referenced by the program (like if you had an entry for sqrt in the table, but didn't call it) the linker will then want (need) to link those functions into your image. This can make it blow up.
Also, if you were taking advantage of global optimizations having this table will likely make those less effective since the compiler will think that all of the functions listed could be accessed via pointer from this list and that it cannot see all of the call points.
Putting static functions in this list is not straight forward. You could do this by changing the table to dynamic and doing it at run time from a function in each module, or possibly by generating a new section in your object file that the table lives in. If you are using gcc:
#define SECTION_REMEMBER(X) \
static const name_addr_t _name_addr##X = \
{.sym_name= #X , .sym_addr = (void *) X } \
__attribute__(section("sym_lookup_table" ) )
And tack a list of these onto the end of each .c file with all of the symbols that you want to remember from that file. This will require linker work so that the linker will know what to do with these members, but then you can iterate over the list by looking at the begin and end of the section that it resides in (I don't know exactly how to do this, but I know it can be done and isn't TOO difficult). This will make having a sorted list more difficult, though. Also, I'm not entirely certain initializing the .sym_name to a string literal's address would not result in cramming the string into this section, but I don't think it would. If it did then this would break things.
You can still use objdump to get a list of the symbols that the object file (probably elf) contains, and then filter this for the symbols you are interested in, and then regenerate the table file the table's members listed.

Resources