Guest User

Untitled

a guest
Jul 23rd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <assert.h>
  4. #include <libtcc.h>
  5.  
  6. FILE *log_func_call;
  7. /* The code dynamically generated can't get access to variable, must provide a
  8. * function. */
  9. FILE *get_log_func_call() {
  10. return log_func_call;
  11. }
  12.  
  13. typedef int (*func_t)(int arg);
  14.  
  15. int foo(int a) {
  16. return a + 1;
  17. }
  18.  
  19. char wrap[] =
  20. "int wrapped(int arg) {"
  21. " int val = origin(arg);"
  22. " printf(\"Inside wrapped function\n\");"
  23. " fprintf(get_log_func_call(), \"arg: %d ret: %d\n\", arg, val);"
  24. " return val;"
  25. "}";
  26.  
  27. func_t create_wrap_function(func_t origin) {
  28. TCCState *s;
  29. func_t func = func;
  30. void *mem;
  31. int size;
  32.  
  33. s = tcc_new();
  34. if (!s) {
  35. fprintf(stderr, "Could not create tcc state\n");
  36. exit(1);
  37. }
  38.  
  39. /* MUST BE CALLED before any compilation */
  40. tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
  41.  
  42. if (tcc_compile_string(s, wrap) == -1)
  43. exit(1);
  44.  
  45. /* as a test, we add a symbol that the compiled program can use.
  46. You may also open a dll with tcc_add_dll() and use symbols from that */
  47. tcc_add_symbol(s, "get_log_func_call", get_log_func_call);
  48. tcc_add_symbol(s, "origin", origin);
  49.  
  50. /* get needed size of the code */
  51. size = tcc_relocate(s, NULL);
  52. if (size == -1)
  53. exit(1);
  54.  
  55. /* allocate memory and copy the code into it */
  56. mem = malloc(size);
  57. tcc_relocate(s, mem);
  58.  
  59. /* get entry symbol */
  60. func = tcc_get_symbol(s, "wrapped");
  61. if (!func) {
  62. fprintf(stderr, "can't get function entry\n");
  63. exit(1);
  64. }
  65.  
  66. /* delete the state */
  67. tcc_delete(s);
  68.  
  69. return func;
  70. }
  71.  
  72. int main(int argc, char* argv[]) {
  73. assert(log_func_call = fopen("log_func_call", "w"));
  74. func_t bar = create_wrap_function(foo);
  75. printf("%d\n", bar(2));
  76.  
  77. return 0;
  78. }
Add Comment
Please, Sign In to add comment