creverse-engineeringghidra

Can Ghidra re-compile and run a short function?


I've picked out a short and "self-contained" function from the Ghidra decompiler. Can Ghidra itself compile the function again so I can try to run it for a couple different values, or would I need to compile it myself with e.g. gcc?

Attaching the function for context:

undefined8 FUN_140041010(char *param_1,longlong param_2,uint param_3)

{
  char *pcVar1;
  uint uVar2;
  ulonglong uVar3;
  
  uVar3 = 0;
  if (param_3 != 0) {
    pcVar1 = param_1;
    do {
      if (pcVar1[param_2 - (longlong)param_1] == '\0') {
        if ((uint)uVar3 < param_3) {
          param_1[uVar3] = '\0';
          return 0;
        }
        break;
      }
      *pcVar1 = pcVar1[param_2 - (longlong)param_1];
      uVar2 = (uint)uVar3 + 1;
      uVar3 = (ulonglong)uVar2;
      pcVar1 = pcVar1 + 1;
    } while (uVar2 < param_3);
  }
  param_1[param_3 - 1] = '\0';
  return 0;
}

Solution

  • Can Ghidra itself compile the function again so I can try to run it for a couple different values

    The P-Code emulator of Ghidra is intended for this kind of scenario. If it is just a short function and doesn't use other libraries, syscalls, etc like your example then the emulator can easily handle this without further effort on your side to emulate library functions. Ghidra knows the semantics of each instruction and converts them to the standardized P-Code format for e.g. decompilation, but this can also be combined with a "P-Code virtual machine".

    It will most likely still involve a bit of scripting, though there exist plugins like TheRomanXpl0it/ghidra-emu-fun to make this easier. There are also more general tutorials if you want to understand the basic idea and usage of the Emulator API (which is not exposed in the GUI in any way)

    If you run into issues while scripting the emulator I would recommend asking specific questions about the emulator API at the dedicated Reverse Engineering Stack Exchange