Statement macros in D - c++

I am porting some code I have written in C++ to D. At one point I introduced a convenience macro, that contains an assignment. Like
#define so_convenient(x) value = some_func(x,#x)
So I am using macros to
access the actual symbol and its string and
make an assignment.
How do I achieve this in D?

You can use a mixin statement to convert a string into code at compile time e.g.:
mixin("value = 123;");
The following function will generate a string containing a statement which would be the closest equivalent of your C macro:
string soConvenient(alias A)()
{
return std.string.format(
'value = someFunc(%1$s, "%1$s");',
__traits(identifier, A));
}
Which you would then use like this:
mixin(soConvenient!x); // equivalent to 'so_convenient(x) in C

Related

Writing a GNU Octave wrapper for a C++ function

I'm trying to edit an GNU Octave wrapper for a C++ function to use it with raspberry pi. I have zero experience with C++ or Octave prior to this (have experience with python and matlab) so I am struggling a little on understanding how this works.
Someone has already written a partial GNU Octave wrapper for a C++ function library as you see here
What I am trying to do is to add additional functions to this wrapper. For example, I would like to edit the block shown here:
DEFUN_DLD (bcm2835_gpio_fsel, args, nargout,
"-*- texinfo -*-\n\
#deftypefn {} bcm2835_gpio_fsel (#var{pin}, #var{mode})\n\
TDOD: document me!\n\
#end deftypefn")
{
octave_value_list retval;
int nargin = args.length ();
if (nargin != 2)
print_usage ();
if (! init_ret)
error ("bcm2835 not initialized");
int pin = args(0).int_value();
int mode = args(1).int_value();
bcm2835_gpio_fsel (pin, mode);
return retval;
}
The purpose is to allow the function bcm2835_gpio_fsel to be able to take a string input. (you can see here for the C++ library) I think the parts I need to change are probably int mode = args.int_value(); to something like string mode = args(1);.
There are several things that I am curious about:
Is my above thinking correct? (re: taking in string input vs int input)
What is the octave_value_list retval; that is written on the top of this code block? I read that "The return type of functions defined with DEFUN_DLD is always octave_value_list." but I'm not quite sure I understand what this means. So it seems like you are initializing a variable that's called retval with type octave_value_list. Is this some form of an array? Not sure...
Thanks a ton!
I will answer question 2 first:
What is the octave_value_list retval; that is written on the top of this code block? I read that "The return type of functions defined with DEFUN_DLD is always octave_value_list." but I'm not quite sure I understand what this means. So it seems like you are initializing a variable that's called retval with type octave_value_list. Is this some form of an array? Not sure...
The octave_value_list is a list of octave_value. An octave_value is a type that wraps anything that you will handle in the Octave interpreter (command-line interface). So, when in Octave you call:
[a, b] = foobar (x, y, z);
The function foobar will receive an octave_value_list with three elements (octave_value), and return an octave_value_list with two arguments.
When you call:
a = foobar (x);
Then the function will still receive and return octave_value_lists, each with one element.
If you're not looking at the Octave C++ headers, then the best alternative is to look at Octave's doxygen documentation. There, you can get an almost complete list of methods for octave_value.
Now, it's easier to answer your first question:
Is my above thinking correct? (re: taking in string input vs int input)
Kind of. You're right in that you can get a string from an argument but you're doing it wrong. string mode = args(1); will fail because args(1) returns an octave_value. Instead, you need to do std::string mode = args(1).string_value();

How to convert condition text to "if" conditional expression?

I'm trying to write in visual c++ to convert a condition text to a simple "if" conditional expression with arithmetic operators, parentheses.
For exemple :
text : "(((a+b)>0)or(c==10))and(d!=e))" or "(a>b)xor(c==d)", etc...
we have normally in c++ style :
int a,b,c,d,e;
...
...
char text[]="(((a+b)>0)or(c==10))and(d!=e))";
if(text_to_if(text)) { .... }
...
...
letters a, b, c, d, e in text correspond with existing integer or float variables.
Please mind that C++ is not an interpreted language. You can not change code, including if statements, at runtime. If you want runtime code evaluation you could try JavaScript with its eval() function 1.
Further on you won't be able to retrieve variable names from your code (except for debugging purposes).

Encrypting / obfuscating a string literal at compile-time

I want to encrypt/encode a string at compile time so that the original string does not appear in the compiled executable.
I've seen several examples but they can't take a string literal as argument. See the following example:
template<char c> struct add_three {
enum { value = c+3 };
};
template <char... Chars> struct EncryptCharsA {
static const char value[sizeof...(Chars) + 1];
};
template<char... Chars>
char const EncryptCharsA<Chars...>::value[sizeof...(Chars) + 1] = {
add_three<Chars>::value...
};
int main() {
std::cout << EncryptCharsA<'A','B','C'>::value << std::endl;
// prints "DEF"
}
I don't want to provide each character separately like it does. My goal is to pass a string literal like follows:
EncryptString<"String to encrypt">::value
There's also some examples like this one:
#define CRYPT8(str) { CRYPT8_(str "\0\0\0\0\0\0\0\0") }
#define CRYPT8_(str) (str)[0] + 1, (str)[1] + 2, (str)[2] + 3, (str)[3] + 4, (str)[4] + 5, (str)[5] + 6, (str)[6] + 7, (str)[7] + 8, '\0'
// calling it
const char str[] = CRYPT8("ntdll");
But it limits the size of the string.
Is there any way to achieve what I want?
I think this question deserves an updated answer.
When I asked this question several years ago, I didn't consider the difference between obfuscation and encryption. Had I known this difference then, I'd have included the term Obfuscation in the title before.
C++11 and C++14 have features that make it possible to implement compile-time string obfuscation (and possibly encryption, although I haven't tried that yet) in an effective and reasonably simple way, and it's already been done.
ADVobfuscator is an obfuscation library created by Sebastien Andrivet that uses C++11/14 to generate compile-time obfuscated code without using any external tool, just C++ code. There's no need to create extra build steps, just include it and use it. I don't know a better compile-time string encryption/obfuscation implementation that doesn't use external tools or build steps. If you do, please share.
It not only obuscates strings, but it has other useful things like a compile-time FSM (Finite State Machine) that can randomly obfuscate function calls, and a compile-time pseudo-random number generator, but these are out of the scope of this answer.
Here's a simple string obfuscation example using ADVobfuscator:
#include "MetaString.h"
using namespace std;
using namespace andrivet::ADVobfuscator;
void Example()
{
/* Example 1 */
// here, the string is compiled in an obfuscated form, and
// it's only deobfuscated at runtime, at the very moment of its use
cout << OBFUSCATED("Now you see me") << endl;
/* Example 2 */
// here, we store the obfuscated string into an object to
// deobfuscate whenever we need to
auto narrator = DEF_OBFUSCATED("Tyler Durden");
// note: although the function is named `decrypt()`, it's still deobfuscation
cout << narrator.decrypt() << endl;
}
You can replace the macros DEF_OBFUSCATED and OBFUSCATED with your own macros. Eg.:
#define _OBF(s) OBFUSCATED(s)
...
cout << _OBF("klapaucius");
How does it work?
If you take a look at the definition of these two macros in MetaString.h, you will see:
#define DEF_OBFUSCATED(str) MetaString<andrivet::ADVobfuscator::MetaRandom<__COUNTER__, 3>::value, andrivet::ADVobfuscator::MetaRandomChar<__COUNTER__>::value, Make_Indexes<sizeof(str) - 1>::type>(str)
#define OBFUSCATED(str) (DEF_OBFUSCATED(str).decrypt())
Basically, there are three different variants of the MetaString class (the core of the string obfuscation). Each has its own obfuscation algorithm. One of these three variants is chosen randomly at compile-time, using the library's pseudo-random number generator (MetaRandom), along with a random char that is used by the chosen algorithm to xor the string characters.
"Hey, but if we do the math, 3 algorithms * 255 possible char keys (0 is not used) = 765 variants of the obfuscated string"
You're right. The same string can only be obfuscated in 765 different ways. If you have a reason to need something safer (you're paranoid / your application demands increased security) you can extend the library and implement your own algorithms, using stronger obfuscation or even encryption (White-Box cryptography is in the lib's roadmap).
Where / how does it store the obfuscated strings?
One thing I find interesting about this implementation is that it doesn't store the obfuscated string in the data section of the executable.
Instead, it is statically stored into the MetaString object itself (on the stack) and the algorithm decodes it in place at runtime. This approach makes it much harder to find the obfuscated strings, statically or at runtime.
You can dive deeper into the implementation by yourself. That's a very good basic obfuscation solution and can be a starting point to a more complex one.
Save yourself a heap of trouble down the line with template metaprogramming and just write a stand alone program that encrypts the string and produces a cpp source file which is then compiled in. This program would run before you compile and would produce a cpp and/or header file that would contain the encrypted string for you to use.
So here is what you start with:
encrypted_string.cpp and encrypted_string.h (which are blank)
A script or standalone app that takes a text file as an input and over writes encrypted_string.cpp and encrypted_string.h
If the script fails, your compiling will fail because there will be references in your code to a variable that does not exist. You could get smarter, but that's enough to get you started.
The reason why the examples you found can't take string literals as template argument is because it's not allowed by the ISO C++ standard. That's because, even though c++ has a string class, a string literal is still a const char *. So, you can't, or shouldn't, alter it (leads to undefined behaviour), even if you can access the characters of such an compile-time string literal.
The only way I see is using defines, as they are handled by the preprocessor before the compiler. Maybe boost will give you a helping hand in that case.
A macro based solution would be to take a variadic argument and pass in each part of the string as a single token. Then stringify the token and encrypt it and concatenate all tokens. The end result would look something like this
CRYPT(m y _ s t r i n g)
Where _ is some placeholder for a whitespace character literal. Horribly messy and I would prefer every other solution over this.
Something like this could do it although the Boost.PP Sequence isn't making it any prettier.
#include <iostream>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#define GARBLE(x) GARBLE_ ## x
#define GARBLE_a x
#define GARBLE_b y
#define GARBLE_c z
#define SEQ (a)(b)(c)
#define MACRO(r, data, elem) BOOST_PP_STRINGIZE(GARBLE(elem))
int main() {
const char* foo = BOOST_PP_SEQ_FOR_EACH(MACRO, _, SEQ);
std::cout << foo << std::endl;
}

how to use strcat with an ENUM?

I have an external tool which is generating an ENUM based on user inputs. Now this ENUM is being used by my C++ code where in i have to select a particular ENUM based on a variable say 'x'. The ENUMS generated are of the form 'ENUM_1', 'ENUM_2', 'ENUM_3'....so on. Now I want the code inside my code such that the appropriate ENUM is chosen based on 'x'. I tried using the strcat function like:
typedef enum ( enum_1, enum_2, enum_3...enum_n) map1;
y=(map1)strcat("enum_", x);
but it gives me the error "Cannot convert from char* to map1.
Can someone pls suggest a method of achieving this.
ThankYou
You can't do this using strcat. From the description what I understand is that you want to convert x to map1. To achieve this, you can do map1 m = (map1)(x-1); See this sample code:
typedef enum { enum_1, enum_2, enum_3} map1;
int main()
{
int x = 1;
map1 m = (map1)(x-1);
}
-1 is required because, the integer value of the enums in map1 starts from 0.
You can't do this. Well you can't do it this way...
Enums aren't evaluated by name at compile time. You'll have to try something with the preprocessor. You can create a define to do something similar. Something like:
#define fn(x) enum_##x
And then call
fn(x)
But this happens when the file gets preprocessed. So you can't access runtime variables. Judging by your code I don't think you'll be able to do what you want.
Good luck though.
Now I want the code inside my code such that the appropriate ENUM is chosen based on 'x'.
Enumerated values are constants and based on the statement I assume that x is an integer data type.
y=(map1)strcat("enum_", x);
strcat(..) passing parameters should be of type char*. And clearly x is not of type char* based on previous statement. It not clear why are you using strcat for achieving this task.
Answer for your subject line: No. You cannot use strcat with enumerated values.

C++ Array of function pointers: assign function using char

I have an array of function pointers like this:
void (*aCallback[10])( void *pPointer );
I am assigning functions to the array like that:
aCallback[0] = func_run;
aCallback[1] = func_go;
aCallback[2] = func_fly;
The names like "run", "go", "fly" are stored in another array.
Is it possible to assign the functions to the function-array using a char? Something like:
char sCallbackName[64];
sprintf(sCallbackName, "func_%s", "run");
aCallback[0] = sCallbackName; //caCallback[0] = "func_run"; doesn't work of course
Not directly, no. The symbol table and other meta-information is generally not available at runtime, C++ is a compiled language.
The typical way to solve it is to use some macro trickery, perhaps along the lines of this:
/* Define a struct literal containing the string version of the n parameter,
* together with a pointer to a symbol built by concatenating "func_" and the
* n parameter.
*
* So DEFINE_CALLBACK(run) will generate the code { "run", func_run }
*/
#define DEFINE_CALLBACK(n) { #n, func_##n }
const struct
{
const char* name;
void (*function)(void *ptr);
} aCallback[] = {
DEFINE_CALLBACK(run),
DEFINE_CALLBACK(go),
DEFINE_CALLBACK(fly)
};
The above code has not been compiled, but it should be at least close.
UPDATE: I added a comment next to the macro to explain it a bit. The # and ## operators are semi-obscure, but totally standard, well-known, and their use always crops up in cases like these.
# is the quoting or stringizing operator.
## is the token concatenation operator.
That is not possible.
The functions are not accessible by name at runtime because the compiler translates a name to a memory address.
This is not possible in vanilla C++.
Scripting languages like PHP has this facility because they are interpreted language. With a language, such as C, which compiles the code prior to running, you don't have such facility.