C++ - Create function at runtime [duplicate] - c++

This question already has answers here:
Is it possible to create a function dynamically, during runtime in C++?
(14 answers)
Closed 8 years ago.
In C++, I have to make some user-defined actions on each cells of a big table.
Because of the size of the table, I'd like not to use interpreted instructions but to compile during runtime a function that I will call on each cell.
The user-defined actions are pretty simple :
if ((state1 && state2) || state3) then change_a_value_in_memory
That's why I don't need to use the LLVM or other JIT libraries.
I hesitate to just use mmap and add the code in hex directly.
I'd like to know if it exists better solutions, or, if not, where I can find the basic format of a C++ function code to directly write it in memory.
Thanks, and sorry for my english :/

This is not the most elegant, but it works always: generate a file with the C++ code of your function, call the compiler using system(), load the generated .so file using dlopen, and use the function!
This will take some time (due to the compiler call), but if you keep the function and maintain a database of the functions you already have, then you can save the amount of compilations.

Related

Is it possible to decompile a C++ executable file [duplicate]

This question already has answers here:
Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?
(16 answers)
Is there a C++ decompiler? [closed]
(5 answers)
Closed 4 years ago.
I lost the source code to an executable file but still have the actual file. Is there any way to retrieve the original C++ code?
Duplicate of this question here.
Yes, it is possible, however when it comes to peeking function bodies and the like, you might have a little less luck. Operating systems like Kali Linux specialize in de-compilation and reverse engineering, so maybe look into a VM of that. And of course, windows has a lot of applications you can use as well to check the application code.
Look over the other question for specific app suggestions. :)
Edit : You will most likely have lost all your logic and function bodies, but you might be able to recover the overall structure. It's your EXE so you might be more familiar with how it was all connected up.
You cannot get the original source code but you can decompile the binary into source code using tools given in this similar question: Is there a C++ decompiler?
The output source code will not look like the original as the compiler will have optimised the original source when generating the executable.
Short answer NO.
Long answer, because C++ doesn't use some intermediate code like C# or Java you cannot decompile the app in some readable format. But if you can read assembly maybe you can save some time.

How can I use NASM as a library? [duplicate]

This question already has answers here:
Convert assembly to machine code in C++
(3 answers)
Closed 6 years ago.
I would like to include NASM itself (the assembler) in a C++ project. Can I compile NASM as a shared library? If not, is there another assembler that works as a C or C++ library?
I checked libyasm but couldn't understand how I can use it to assemble my code.
Woah, this exploded when I was away.
I had solved this problem by tampering with the YASM source code, and totally forgot about the question in SO as it received absolutely no attention 8 months ago. Below are the details, followed by a better suggestion.
For the project that I had in mind, I needed to use YASM as a library, and I was in a hurry because I was doing this for a company. Back then there were no good libraries that I was aware of; and I had concluded that getting used to the LLVM framework was an overkill for the task (because all I wanted was to assemble singular x86 - x86_64 instructions and receive the bytes).
So I downloaded the source code for YASM.
Upon meddling with the code for a while, I noticed that the executable receives the file paths for input and output files; and passes these two strings along. I wanted char arrays in memory for the input and output; not files. So I figured, maybe if I could find all FILE pointers that are passed around, I can convert them to char pointers, and change every file read/write to array operations.
This turned out to be even more cumbersome than it sounds. Apparently YASM does not open input/output files once and uses the same FILE pointers; instead it passes around copies of the filepath strings. I needed a script that could make all the necessary changes for me, this wasn't good for me.
Eventually, I found all fopen/fclose calls in the program with a script, and replaced them with my_fopen/my_fclose. For each file that I made these replacements, I included my header file in which I implemented these two functions.
In both of these functions, I checked the incoming string, compared it with "fake_file". If they are equal, I passed a 'fake' FILE pointer pointing to two portions of memory, obtained from the function calls fmemopen and open_memstream. Otherwise I simply called the actual fopen/fclose functions. In other words, I redirected these two calls (only for a given filename) to a memory file. Then, I called the library with the filename parameter set to 'fake_file'.
Since I have had limited myself to Linux at that point, this approach worked for me. I also found out (using Valgrind) that there was a memory leak in the library version, so I wrote a very primitive garbage collector for it. Basically I wrapped malloc's etc. to keep track of all allocations that are not freed, and clean them after each execution.
This approach also allowed me to automate these changes using a script. Unfortunately I did all these in a company so I cannot leak any actual code.
Better suggestion:
As of May 31, 2016; you can use Keystone Engine instead. It is "based on LLVM, but it goes much further with a lot more to offer." The disassembly engine Capstone and this are a near perfect couple for assembly and disassembly. If you need either of these components, I suggest these instead of doing the hacks I described. Both of these engines are currently being developed; and even though Keystone has some small bugs, Capstone is very robust at the moment.
TL;DR: Use keystone.

How to generate code using a loop in c++? [duplicate]

This question already has answers here:
How can I convert string to code at run time
(4 answers)
Closed 9 years ago.
Is it possible to convert a raw string to code in c++?
For example I have a string
string s = "cout << "Hello World";";
I want to generate that code programatically. Maybe i want to insert that code in various parts of the program dynamically.
cout << "Hello World";
Also, is it possible to generate code using loops in c++ maybe using pre-processor directives?
It looks like you want something akin to the eval function provided by Lisp, Python, perl, and many other languages.
There is no such capability in C++. It just doesn't exist, by design.
One way to get around this missing functionality is to make your program write a program, store it in a file, invoke the compiler, and invoke the executable generated by the compiler. That's rather ugly. Anything you do is going to be rather ugly.
Is it possible to convert a raw string to code in c++?
C++ is typically a compiled language. This makes what you're trying to do tricky. In order to achieve what you're saying, you'd need to either have the code interpreted at runtime (in which case you'd be better served by binding to a scripting language such as Python or Lua), or embed or call a C++ compiler and pass the code to that, then run it.
It is possible that this is a XY problem and that the solution you are looking at is overly complicated for the actual root problem you are trying to solve. It may be an idea to put up a description of why you're trying to do this, as there may be a much simpler way to achieve the end result you want.

How do I "compile" an expression in c++ at runtime? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
compile and run c++ code runtime
I want to take as an input an expression from the user as a string and compile it into a callable c++ function. Are there any tools that allow you to do this easily?
Basically, How do I compile an Expression Tree into a callable method, C#? seems similar to what I want to do except that I need to do this in c++ and not c#.
I can certainly make a sort of generic evaluator using lex and yacc but I don't want to have to parse the string every time. Basically this expression will run in a critical inner loop so I'm looking for a way to "compile" it at run-time.
It's not easy... If you want my two cents, I will follow these steps:
Create an interface for the code that you must create at runtime. At first, you create an interface for what you can do. For example your class must inherit from a pure virtual base class that will represent your interface. Take care that your program will use not arbitrary code, but code created in a specific way, because it must know how to use it.
Call the compiler from inside your program. The compiler should create a library from your source code. You can use a predefined project that you store somewhere, and then replace its source file with your own. So it can be easy to obtain a right library.
Put your library in a specified source where you can find it.
Load the library at runtime. If you search, you will see that it's possible to load dynamic libraries at runtime, not only at linking time (in this way, for example, you can create plugins for programs). So your program can load your library and use it. For example you can find some information here.
But, as others have said, it's not a trivial task.
EDIT: Another solution is to check a parser like boost::spirit::qi, that is well used can give extremly helpful results.
You have to parse the expression to an abstract syntax tree and walk it or evaluate it in-place. Something like this should satisfy your needs for a simple mathematical expression.
You can write your mini-interpreter. With the commands same with c++ (not all of them). Of course your compiler will optimize it but not sure how much. I did it for assembly in qbasic (mov, add, sub...) but it was quite slow because of being an interpreter of an interpreter :D
Did you think about Evolutionary computation and fitness functions? Worth looking at.
You can create a data structure that represents your parsed expression tree, and the overhead of evaluating that at runtime will be small compared to parsing the string every time.
Actually getting a callable method in C++ will be quite difficult, in that you would have to generate object code and dynamically load it into your program. This would duplicate a lot of what the whole compiler tool-chain does.

How to calculate the MD5 of a char* using C++ [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
In C++, How to get MD5 hash of a file?
I am currently using Ubuntu and am wishing to calculate the MD5 of a char*. was wondering if there is a pre-installed library that would just need including, or would I have to download a specially designed one?
Include openssl/MD5.h and use the following to calculate the hash
MD5(<characters>, <length of it>, <the result(pointer)>);
Have a look at hashlib++ or Crypto API.
I would rephrase the question. In the context of C++, you're asking for the MD5 sum of a single pointer to char, which is practically meaningless.
That 'char *' could refer to a location in memory that refers to the file content you are after, in which case you're going to need a size somewhere, or it could refer to a null-terminated string, or a pascal-string, or, really, anything else.
With ubuntu, I'd do something like 'apt-cache search md5' and see what you get. On my debian system, libgcrypt11 looks intriguing.