Package: ghidrecomp
Ghidrecomp - Command Line Ghidra DecompilerAboutThis Python command line tool decompiles all functions of a binary and writes them to a directory in separateCfiles:flowchart LR

a(filename ) --> b[ghidrecomp]
a2[(Symbol Server)] --> b

b --> e(Ghidra Project Files)
b --> output

subgraph output

  subgraph decompilations
      direction LR
      i(func1.c)
      h(func2.c)
      f(funcB.c)
  end

  subgraph callgraphs
      direction LR
      j(callgraph1.md)
      k(callgraph2.md)
      l(callgraphN.md)
  end

  subgraph bsim-xml
      direction LR
      n(sig-md5-bin1.xml)
      m(sig-md5-bin2.xml)
      o(sig-md5-binN.xml)
  end

endOr a single fileCand header file with--cppexport:flowchart LR

a(filename ) --> b[ghidrecomp]
a2[(Symbol Server)] --> b

b --> e(Ghidra Project Files)

b --> singlefile 


subgraph singlefile
  direction LR
  s1(all_funcs.c)
  s2(all_funcs.h)
endThe main purpose for this is to use the decomplilations for research and analysis. The tool relies onGhidrafor decompilation and communicates to Ghidra withjpypeviapyhidra.TOCGhidrecomp - Command Line Ghidra DecompilerAboutTOCFeaturesUsageOutput Files TreeExample Usage with Windows afd.sys:Command lineOutputDecompilation Output DirExample usage in Docker containerCommand (Host)Run in docker on /bin/lsOutputDecompilation Output DirExample Usage with Windows afd.sys Callgraph:Command lineOutputSample Calling Callgraph Output AfdRestartDgConnect:Sample MindMap Output for AfdRestartDgConnectExample BSim signature generationCommand lineOutputFiles generatedInstallationWindowsLinux / MacDevcontainer / DockerOption 1 - DevcontainerOption 2 - DockerFeaturesall these features are ultimately provided by GhidraDecompile all the functions (threaded)to a folder (-o OUTPUT_PATH)to a single c file and header file (--cppexport)Auto-downloaded symbols for supported symbol servers (-s SYMBOLS_PATH)https://msdl.microsoft.com/download/symbols/https://chromium-browser-symsrv.commondatastorage.googleapis.com/https://symbols.mozilla.org/https://software.intel.com/sites/downloads/symbols/https://driver-symbols.nvidia.com/https://download.amd.com/dir/bin/Specify the pdb for the binary (--sym-file-path)Filter functions to decompile that match regex (--filter)Apply custom data types (--gdt)Usageusage: ghidrecomp [-h] [--cppexport] [--filter FILTERS] [--project-path PROJECT_PATH] [--gdt [GDT]] [-o OUTPUT_PATH] [-v] [--skip-cache]
                  [--sym-file-path SYM_FILE_PATH | -s SYMBOLS_PATH | --skip-symbols] [-t THREAD_COUNT] [--va] [--fa]
                  [--max-ram-percent MAX_RAM_PERCENT] [--print-flags] [--callgraphs] [--callgraph-filter CALLGRAPH_FILTER] [--mdd MAX_DISPLAY_DEPTH]
                  [--max-time-cg-gen MAX_TIME_CG_GEN] [--cg-direction {calling,called,both}] [--bsim] [--bsim-sig-path BSIM_SIG_PATH]
                  [--bsim-template BSIM_TEMPLATE] [--bsim-cat BSIM_CAT]
                  bin

ghidrecomp - A Command Line Ghidra Decompiler

positional arguments:
  bin                   Path to binary used for analysis

options:
  -h, --help            show this help message and exit
  --cppexport           Use Ghidras CppExporter to decompile to single file (default: False)
  --filter FILTERS      Regex match for function name (default: None)
  --project-path PROJECT_PATH
                        Path to base ghidra projects (default: ghidra_projects)
  --gdt [GDT]           Additional GDT to apply (default: None)
  -o OUTPUT_PATH, --output-path OUTPUT_PATH
                        Location for all decompilations (default: ghidrecomps)
  -v, --version         show program's version number and exit
  --skip-cache          Skip cached and genearate new decomp and callgraphs. (default: False)
  --sym-file-path SYM_FILE_PATH
                        Specify single pdb symbol file for bin (default: None)
  -s SYMBOLS_PATH, --symbols-path SYMBOLS_PATH
                        Path for local symbols directory (default: symbols)
  --skip-symbols        Do not apply symbols (default: False)
  -t THREAD_COUNT, --thread-count THREAD_COUNT
                        Threads to use for processing. Defaults to cpu count (default: 12)
  --va                  Enable verbose analysis (default: False)
  --fa                  Force new analysis (even if already analyzed) (default: False)

JVM Options:
  --max-ram-percent MAX_RAM_PERCENT
                        Set JVM Max Ram % of host RAM (default: 50.0)
  --print-flags         Print JVM flags at start (default: False)

Callgraph Options:
  --callgraphs          Generate callgraph markdown (default: False)
  --callgraph-filter CALLGRAPH_FILTER
                        Only generate callgraphs for functions matching filter (default: .)
  --mdd MAX_DISPLAY_DEPTH, --max-display-depth MAX_DISPLAY_DEPTH
                        Max Depth for graph generation (default: None)
  --max-time-cg-gen MAX_TIME_CG_GEN
                        Max time in seconds to wait for callgraph gen. (default: 5)
  --cg-direction {calling,called,both}
                        Direction for callgraph. (default: calling)

BSim Options:
  --bsim                Generate BSim function feature vector signatures (default: False)
  --bsim-sig-path BSIM_SIG_PATH
                        Path to store BSim xml sigs (default: bsim-xmls)
  --bsim-template BSIM_TEMPLATE
                        BSim database template (default: medium_nosize)
  --bsim-cat BSIM_CAT   BSim category. (type:value) --bsim-cat color:red (default: None)Output Files TreeAll files:$tree-L2ghidrecomps/|more
ghidrecomps/
├──bins
│├──afd.sys.10.0.22621.1415-b4c4b6ef5980df8440fb26daffb4118f
│└──ls_aarch64-fffefca59f1dcb04e318b6b26fa1b50e
├──bsim-xmls
│└──sigs_fffefca59f1dcb04e318b6b26fa1b50e_ls_aarch64
├──ghidra_projects
│├──afd.sys.10.0.22621.1415-b4c4b6ef5980df8440fb26daffb4118f
│└──ls_aarch64-fffefca59f1dcb04e318b6b26fa1b50e
└──symbols├──000admin├──afd.pdb└──pingme.txtDecomps and callgraphs:$tree-L2ghidrecomps/bins/
ghidrecomps/bins/
├──afd.sys.10.0.22621.1415-b4c4b6ef5980df8440fb26daffb4118f
│├──callgraphs
│└──decomps
└──ls_aarch64-fffefca59f1dcb04e318b6b26fa1b50e└──decompsExample Usage with Windows afd.sys:Command linewgethttps://msdl.microsoft.com/download/symbols/afd.sys/50989142a9000/afd.sys-Oafd.sys.10.0.22621.1415
ghidrecompafd.sys.10.0.22621.1415OutputStartingdecompliations:Namespace(bin='tests/data/afd.sys.10.0.22621.1344',cppexport=False,filters=None,project_path='.ghidra_projects',output_path='decompilations',sym_file_path=None,symbols_path='.symbols',skip_symbols=False,thread_count=8,va=False)INFOUsinglogconfigfile:jar:file:/ghidra/Ghidra/Framework/Generic/lib/Generic.jar!/generic.log4j.xml(LoggingInitialization)INFOUsinglogfile:/home/vscode/.ghidra/.ghidra_10.2.3_PUBLIC/application.log(LoggingInitialization)INFOLoadinguserpreferences:/home/vscode/.ghidra/.ghidra_10.2.3_PUBLIC/preferences(Preferences)INFOClasssearchcomplete(766ms)(ClassSearcher)INFOInitializingSSLContext(SSLContextInitializer)INFOInitializingRandomNumberGenerator...(SecureRandomFactory)INFORandomNumberGeneratorinitializationcomplete:NativePRNGNonBlocking(SecureRandomFactory)INFOTrustmanagerdisabled,cacertshavenotbeenset(ApplicationTrustManagerFactory)INFOCreatingproject:/workspaces/ghidrecomp/.ghidra_projects/afd.sys.10.0.22621.1344/afd.sys.10.0.22621.1344(DefaultProject)INFOUsingLoader:PortableExecutable(PE)(AutoImporter)SettingupSymbolServerforsymbols...
path:.symbolslevel:1Loadedwellknown/ghidra/Ghidra/Configurations/Public_Release/data/PDB_SYMBOL_SERVER_URLS.pdburl' length: 883'SymbolServerConfiguredpath:SymbolServerService:symbolStore:LocalSymbolStore:[rootDir:/workspaces/ghidrecomp/.symbols,storageLevel:-1],symbolServers:HttpSymbolServer:[url:https://msdl.microsoft.com/download/symbols/,storageLevel:-1]HttpSymbolServer:[url:https://chromium-browser-symsrv.commondatastorage.googleapis.com/,storageLevel:-1]HttpSymbolServer:[url:https://symbols.mozilla.org/,storageLevel:-1]HttpSymbolServer:[url:https://software.intel.com/sites/downloads/symbols/,storageLevel:-1]HttpSymbolServer:[url:https://driver-symbols.nvidia.com/,storageLevel:-1]HttpSymbolServer:[url:https://download.amd.com/dir/bin/,storageLevel:-1]Analyzingprogramafd.sys.10.0.22621.1344
INFOPDBanalyzerparsingfile:/workspaces/ghidrecomp/.symbols/afd.pdb/14FBAE3662AD9F7B9D33AA9228D2554A1/afd.pdb(PdbUniversalAnalyzer)INFOResolvetime:0mS(DefaultPdbApplicator)INFOresolveCount:0(DefaultPdbApplicator)INFOPDBTerminatedNormally(DefaultPdbApplicator)WARNDecompiling1c0001340,pcodeerrorat1c000000c:Unabletoresolveconstructorat1c000000c(DecompileCallback)INFOPackeddatabasecache:/tmp/vscode-Ghidra/packed-db-cache(PackedDatabaseCache)WARNDecompiling1c0001340,pcodeerrorat1c000000c:Unabletoresolveconstructorat1c000000c(DecompileCallback)INFO-----------------------------------------------------ASCIIStrings0.343secsApplyDataArchives0.548secsCallConventionID0.025secsCall-FixupInstaller0.013secsCreateAddressTables0.039secsCreateAddressTables-OneTime0.076secsCreateFunction0.232secsDataReference0.126secsDecompilerParameterID10.939secsDecompilerSwitchAnalysis0.442secsDemanglerMicrosoft0.089secsDisassemble0.007secsDisassembleEntryPoints1.959secsDisassembleEntryPoints-OneTime0.005secsEmbeddedMedia0.020secsExternalEntryReferences0.000secsFunctionID0.805secsFunctionStartSearch0.038secsNon-ReturningFunctions-Discovered0.132secsNon-ReturningFunctions-Known0.012secsPDBUniversal2.810secsReference0.104secsScalarOperandReferences0.601secsSharedReturnCalls0.219secsStack5.164secsSubroutineReferences0.113secsSubroutineReferences-OneTime0.026secsWindowsx86PEExceptionHandling0.027secsWindowsx86PERTTIAnalyzer0.005secsWindowsx86ThreadEnvironmentBlock(TEB)Analyzer0.038secsWindowsResourceReference0.124secsx86ConstantReferenceAnalyzer5.755secs
-----------------------------------------------------TotalTime30secs
-----------------------------------------------------(AutoAnalysisManager)Decompiling1275functionsusing8threads
Setup8decompliers
WARNDecompiling1c0001340,pcodeerrorat1c000000c:Unabletoresolveconstructorat1c000000c(DecompileCallback)Completed100and7%
Completed200and15%
Completed300and23%
Completed400and31%
Completed500and39%
Completed600and47%
Completed700and54%
Completed800and62%
Completed900and70%
Completed1000and78%
Completed1100and86%
Completed1200and94%
Decompiled1275functionsforafd.sys.10.0.22621.1344in13.469883680343628
Wrote1275decompilationsforafd.sys.10.0.22621.1344todecompilations/afd.sys.10.0.22621.1344in3.174959659576416Decompilation Output Dir$treeghidrecomps|more
ghidrecomps/
└──afd.sys├──AFDETW_TRACEDATA_INDICATION-1c0008d00.c├──AFDETW_TRACEDISCONNECT-1c000f884.c├──AFDETW_TRACELISTEN-1c0016778.c├──AFDETW_TRACEOPTION-1c0012660.c├──AFDETW_TRACERECV-1c0001e38.c├──AFDETW_TRACERECVDATAGRAM-1c0009ef0.c├──AFDETW_TRACESEND-1c000d19c.c├──AFDETW_TRACESENDDATAGRAM-1c0007d10.c├──AFDETW_TRACESENDMSG-1c0015afc.c├──AFDETW_TRACESENDTO-1c00162dc.c├──AFDETW_TRACESTATUS-1c00204d2.c├──AFDETW_TRACETRANSFER-1c004189c.c├──AFDETW_TRACEWAITLISTEN-1c0013674.c├──AFD_PCW_INCREMENT_DROPPED_DATAGRAMS-1c00208e4.c├──AFD_PCW_INCREMENT_REJECTED_CONNECTIONS-1c0032aa4.c├──AfdAbortConnection-1c0033ec4.c├──AfdAbortTPackets-1c003d5ec.c├──AfdAccept-1c0018300.c├──AfdAcceptCore-1c00187d8.c├──AfdAcquireReadLock-1c0020b54.c├──AfdAcquireReadLockAtDpcLevel-1c000b0f4.c├──AfdAcquireWriteLock-1c001b8ac.c├──AfdAddAddressHandler-1c00662f0.c├──AfdAddConnectedReference-1c000f334.c├──AfdAddConnectionToTimerWheel-1c0036520.c├──AfdAddFreeConnection-1c006d7cc.c├──AfdAddressListChange$filt$0-1c001dcb7.c├──AfdAddressListChange$filt$1-1c001dce0.c├──AfdBuildSendMsgTracker-1c00682ac.c
...severallinesomitted$catdecompilations/afd.sys.10.0.22621.1415/AfdGetRemoteAddress-1c0065500.cvoidAfdGetRemoteAddress(longlongparam_1,undefined8param_2,charparam_3,undefined8param_4,undefined8param_5,void*param_6,uintparam_7,ulonglong*param_8){ushortuVar1;short*psVar2;uintuVar3;ulonglonguVar4;undefineduVar5;void*_Src;undefined8unaff_RBX;undefined8unaff_RSI;undefinedunaff_DIL;charcVar7;ulonglong_Size;undefinedunaff_R14B;undefinedunaff_R15B;undefinedunaff_retaddr;undefineduVar8;short*psVar9;undefinedin_stack_ffffffffffffffe0;short*psVar6;psVar2=*(short**)(param_1+0x18);*param_8=0;psVar6=psVar2;cVar7=param_3;psVar9=psVar2;uVar4=AfdLockEndpointContext((longlong)psVar2);uVar5=SUB81(psVar6,0);uVar8=SUB81(psVar9,0);if(((uVar4!=0)&&(*psVar2==-0x502e))&&(*(char*)(psVar2+1)=='\x04')){uVar1=psVar2[0x5d];uVar5=(undefined)uVar1;uVar3=(uint)(ushort)psVar2[0x5c]+(uint)uVar1;if(uVar3<*(uint*)(psVar2+0x74)||uVar3==*(uint*)(psVar2+0x74)){if(uVar1<=param_7){if(param_3!='\0'){ProbeForWrite(param_6,uVar1,1);}_Size=(ulonglong)(ushort)psVar2[0x5d];_Src=(void*)((ushort)psVar2[0x5c]+uVar4);memcpy(param_6,_Src,_Size);*param_8=(ulonglong)*(uint*)(psVar2+0x74);FUN_1c00655e1((char)param_6,(char)_Src,(char)_Size,(undefined)param_4,in_stack_ffffffffffffffe0,unaff_R15B,unaff_R14B,unaff_DIL,unaff_retaddr,uVar8,unaff_RBX,unaff_RSI);return;}FUN_1c00655e1(uVar5,(undefined)param_2,cVar7,(undefined)param_4,in_stack_ffffffffffffffe0,unaff_R15B,unaff_R14B,unaff_DIL,unaff_retaddr,uVar8,unaff_RBX,unaff_RSI);return;}}FUN_1c00655e1(uVar5,(undefined)param_2,cVar7,(undefined)param_4,in_stack_ffffffffffffffe0,unaff_R15B,unaff_R14B,unaff_DIL,unaff_retaddr,uVar8,unaff_RBX,unaff_RSI);return;}Example usage in Docker containerCommand (Host)%mkdirghidrecomps
%dockerrun--rm-it-v$(pwd)/ghidrecomps:/ghidrecompsghcr.io/clearbluejar/ghidrecomp:latest
Unabletofindimage'ghcr.io/clearbluejar/ghidrecomp:latest'locally
latest:Pullingfromclearbluejar/ghidrecomp
df2021ddb7d6:Alreadyexists
8d647f1dd7e7:Alreadyexists
5cdd9a70365f:Alreadyexists
95089c600b36:Alreadyexists
031bfcddba4a:Alreadyexists
3e388e9ee67f:Alreadyexists
c8dd6e41498c:Alreadyexists
6997e1686b99:Alreadyexists
ee33bc143a6a:Alreadyexists
5be89ff28daf:Alreadyexists
ba22b50e2816:Alreadyexists
a10ea6edf9a9:Alreadyexists
01795477b75e:Alreadyexists
85b3b893a1c1:Alreadyexists
53738c41768c:Alreadyexists
bd57d1a46c3c:Alreadyexists
117d78b0cfb7:Alreadyexists
15235f090f28:Alreadyexists
4f4fb700ef54:Pullcomplete13c463db881b:Pullcompletedac212319919:Pullcomplete6855adc3f8b8:Pullcomplete96069363e29e:Pullcompleteb7f172785aba:Pullcomplete05aed184d971:Pullcomplete611f58da3b2c:PullcompleteDigest:sha256:1e7d47267b7a0a31805822c11f891cd502485a42c88bb0ad6292a34e930c6108
Status:Downloadednewerimageforghcr.io/clearbluejar/ghidrecomp:latest
usage:ghidrecomp[-h][--cppexport][--filterFILTERS][--project-pathPROJECT_PATH][--gdt[GDT]][-oOUTPUT_PATH][-v][--skip-cache][--sym-file-pathSYM_FILE_PATH|-sSYMBOLS_PATH|--skip-symbols][-tTHREAD_COUNT][--va][--fa][--max-ram-percentMAX_RAM_PERCENT][--print-flags][--callgraphs][--callgraph-filterCALLGRAPH_FILTER][--mddMAX_DISPLAY_DEPTH][--max-time-cg-genMAX_TIME_CG_GEN][--cg-direction{calling,called,both}]bin
ghidrecomp:error:thefollowingargumentsarerequired:binRun in docker on /bin/ls$dockerrun--rm-it-v$(pwd)/ghidrecomps:/ghidrecompsghcr.io/clearbluejar/ghidrecomp:latest/bin/lsOutputStartingdecompliations:Namespace(bin='/bin/ls',cppexport=False,filters=None,project_path='.ghidra_projects',gdt=None,output_path='decompilations',skip_cache=False,sym_file_path=None,symbols_path='.symbols',skip_symbols=False,thread_count=12,va=False,fa=False,max_ram_percent=50.0,print_flags=False,callgraphs=False,callgraph_filter='.',max_display_depth=None,max_time_cg_gen=5,cg_direction='calling')INFOUsinglogconfigfile:jar:file:/ghidra/Ghidra/Framework/Generic/lib/Generic.jar!/generic.log4j.xml(LoggingInitialization)INFOUsinglogfile:/home/vscode/.ghidra/.ghidra_11.0_PUBLIC/application.log(LoggingInitialization)INFOLoadinguserpreferences:/home/vscode/.ghidra/.ghidra_11.0_PUBLIC/preferences(Preferences)INFOSearchingforclasses...(ClassSearcher)INFOClasssearchcomplete(566ms)(ClassSearcher)INFOInitializingSSLContext(SSLContextInitializer)INFOInitializingRandomNumberGenerator...(SecureRandomFactory)INFORandomNumberGeneratorinitializationcomplete:NativePRNGNonBlocking(SecureRandomFactory)INFOTrustmanagerdisabled,cacertshavenotbeenset(ApplicationTrustManagerFactory)INFOCreatingproject:/home/vscode/.ghidra_projects/ls/ls(DefaultProject)INFOStartingcachecleanup:/tmp/vscode-Ghidra/fscache2(FileCacheMaintenanceDaemon)INFOFinishedcachecleanup,estimatedstorageused:0(FileCacheMaintenanceDaemon)INFOUsingLoader:ExecutableandLinkingFormat(ELF)(AutoImporter)INFOUsingLanguage/Compiler:AARCH64:LE:64:v8A:default(AutoImporter)SettingupSymbolServerforsymbols...
path:.symbolslevel:1Loadedwellknown/ghidra/Ghidra/Configurations/Public_Release/data/PDB_SYMBOL_SERVER_URLS.pdburl' length: 883'SymbolServerConfiguredpath:SymbolServerService:symbolStore:LocalSymbolStore:[rootDir:/home/vscode/.symbols,storageLevel:-1],symbolServers:HttpSymbolServer:[url:https://msdl.microsoft.com/download/symbols/,storageLevel:-1]HttpSymbolServer:[url:https://chromium-browser-symsrv.commondatastorage.googleapis.com/,storageLevel:-1]HttpSymbolServer:[url:https://symbols.mozilla.org/,storageLevel:-1]HttpSymbolServer:[url:https://software.intel.com/sites/downloads/symbols/,storageLevel:-1]HttpSymbolServer:[url:https://driver-symbols.nvidia.com/,storageLevel:-1]HttpSymbolServer:[url:https://download.amd.com/dir/bin/,storageLevel:-1]Failedtofindpdbforls-.ProgramDB
Analyzingprogramls...
Runninganalyzers...
INFODWARFexternaldebuginformationfound:ExternalDebugInfo[filename=127c37a4c459cf01639f6ded2fcf11a49d3da9.debug,crc=2d1e7054,hash=9f127c37a4c459cf01639f6ded2fcf11a49d3da9](ExternalDebugFilesService)INFOUnabletofindDWARFinformation,skippingDWARFanalysis(DWARFAnalyzer)INFOPackeddatabasecache:/tmp/vscode-Ghidra/packed-db-cache(PackedDatabaseCache)INFOApplieddatatypearchive:generic_clib_64(ApplyDataArchiveAnalyzer)INFO-----------------------------------------------------AARCH64ELFPLTThunks0.063secsASCIIStrings0.139secsApplyDataArchives0.575secsBasicConstantReferenceAnalyzer0.867secsCallConventionID0.004secsCall-FixupInstaller0.005secsCreateAddressTables0.022secsCreateAddressTables-OneTime0.012secsCreateFunction0.000secsDWARF0.007secsDataReference0.022secsDecompilerSwitchAnalysis0.982secsDemanglerGNU0.027secsDisassemble0.008secsDisassembleEntryPoints0.521secsEmbeddedMedia0.008secsExternalEntryReferences0.000secsFunctionStartSearch0.017secsFunctionStartSearchAfterCode0.009secsFunctionStartSearchAfterData0.010secsFunctionStartSearchdelayed-OneTime0.003secsGCCExceptionHandlers0.196secsNon-ReturningFunctions-Discovered0.024secsNon-ReturningFunctions-Known0.003secsReference0.064secsSharedReturnCalls0.035secsStack0.984secsSubroutineReferences0.023secs
-----------------------------------------------------TotalTime4secs
-----------------------------------------------------(AutoAnalysisManager)INFOOpeningproject:/home/vscode/.ghidra_projects/ls/ls(DefaultProject)Decompiling566functionsusing12threads
Setup12decompliers
Decompiled100and17%
Decompiled200and35%
Decompiled300and53%
Decompiled400and70%
Decompiled500and88%
Decompiled566functionsforlsin1.92808556556701660decompilationsalreadyexisted.
Wrote566decompilationsforlstodecompilations/lsin0.06782746315002441Decompilation Output Dirvscode➜/tmp$treeghidrecomps
ghidrecomps
└──ls├──_ITM_deregisterTMCloneTable-00134078.c├──_ITM_registerTMCloneTable-00134358.c├──__DT_FINI-00118930.c├──__DT_INIT-00103730.c├──__assert_fail-00103da0.c├──__assert_fail-00134370.c├──__ctype_b_loc-00103c00.c├──__ctype_b_loc-00134288.c├──__libc_start_main-00134190.c├──__lxstat-00103ce0.c├──__lxstat-001342f8.c├──exit-00134050.c├──fclose-00103990.c├──fclose-00134138.c├──fflush-00103ca0.c├──fflush-001342d8.c├──fflush_unlocked-00103c90.c├──fflush_unlocked-001342d0.c├──fgetfilecon-001037a0.c├──fgetfilecon-00134018.c├──fileno-00103950.c├──fileno-00134110.c├──fnmatch-00103c80.c├──fnmatch-001342c8.c├──fputc_unlocked-00103d20.c├──fputc_unlocked-00134320.c├──fputs_unlocked-00103d40.c
...severalmoreomittedcatdecompilations/ls/FUN_0010eb20-0010eb20.cvoid*FUN_0010eb20(void*param_1,char*param_2,void**param_3){size_t__n;longlVar1;longlVar2;size_t__n_00;void*__dest;undefined*puVar3;ulonguVar4;undefinedlocal_41;lVar1=FUN_0010e740();lVar2=FUN_0010e7a0(lVar1);__n=(lVar1-(long)param_1)+lVar2;__n_00=strlen(param_2);if(lVar2==0){local_41=0x2e;if(*param_2!='/'){local_41=0;}uVar4=(ulong)(*param_2=='/');}elseif(*(char*)((long)param_1+(__n-1))=='/'){local_41=0;uVar4=0;}else{local_41=0x2f;if(*param_2=='/'){local_41=0;}uVar4=(ulong)(*param_2!='/');}__dest=malloc(__n+1+__n_00+uVar4);if(__dest!=(void*)0x0){puVar3=(undefined*)mempcpy(__dest,param_1,__n);*puVar3=local_41;if(param_3!=(void**)0x0){*param_3=puVar3+uVar4;}puVar3=(undefined*)mempcpy(puVar3+uVar4,param_2,__n_00);*puVar3=0;}return__dest;}Example Usage with Windows afd.sys Callgraph:Command lineGenerate a decompilation and callgraph of all functions matching the function--filter AfdRestartand--callgraph-filter AfdRestart.ghidrecomptests/data/afd.sys.10.0.22621.1415--callgraph-filterAfdRestart--filterAfdRestart--callgraphsOutputStartingdecompliations:Namespace(bin='tests/data/afd.sys.10.0.22621.1415',cppexport=False,filters=['AfdRestart'],project_path='.ghidra_projects',gdt=None,output_path='decompilations',skip_cache=True,sym_file_path=None,symbols_path='.symbols',skip_symbols=False,thread_count=8,va=False,fa=False,max_ram_percent=50.0,print_flags=False,callgraphs=True,callgraph_filter='AfdRestart',max_display_depth=None,max_time_cg_gen=5,cg_direction='calling')INFOUsinglogconfigfile:jar:file:/ghidra/Ghidra/Framework/Generic/lib/Generic.jar!/generic.log4j.xml(LoggingInitialization)INFOUsinglogfile:/home/vscode/.ghidra/.ghidra_10.3_PUBLIC/application.log(LoggingInitialization)INFOLoadinguserpreferences:/home/vscode/.ghidra/.ghidra_10.3_PUBLIC/preferences(Preferences)INFOSearchingforclasses...(ClassSearcher)INFOClasssearchcomplete(710ms)(ClassSearcher)INFOInitializingSSLContext(SSLContextInitializer)INFOInitializingRandomNumberGenerator...(SecureRandomFactory)INFORandomNumberGeneratorinitializationcomplete:NativePRNGNonBlocking(SecureRandomFactory)INFOTrustmanagerdisabled,cacertshavenotbeenset(ApplicationTrustManagerFactory)INFOOpeningproject:/workspaces/ghidrecomp/.ghidra_projects/afd.sys.10.0.22621.1415/afd.sys.10.0.22621.1415(DefaultProject)SettingupSymbolServerforsymbols...
path:.symbolslevel:1Loadedwellknown/ghidra/Ghidra/Configurations/Public_Release/data/PDB_SYMBOL_SERVER_URLS.pdburl' length: 883'SymbolServerConfiguredpath:SymbolServerService:symbolStore:LocalSymbolStore:[rootDir:/workspaces/ghidrecomp/.symbols,storageLevel:-1],symbolServers:HttpSymbolServer:[url:https://msdl.microsoft.com/download/symbols/,storageLevel:-1]HttpSymbolServer:[url:https://chromium-browser-symsrv.commondatastorage.googleapis.com/,storageLevel:-1]HttpSymbolServer:[url:https://symbols.mozilla.org/,storageLevel:-1]HttpSymbolServer:[url:https://software.intel.com/sites/downloads/symbols/,storageLevel:-1]HttpSymbolServer:[url:https://driver-symbols.nvidia.com/,storageLevel:-1]HttpSymbolServer:[url:https://download.amd.com/dir/bin/,storageLevel:-1]Usingfilegdts:[windows_vs12_64]afd.sys.10.0.22621.1415-.ProgramDBalreadyanalyzed...skipping
INFOOpeningproject:/workspaces/ghidrecomp/.ghidra_projects/afd.sys.10.0.22621.1415/afd.sys.10.0.22621.1415(DefaultProject)Skipped1241functionsthatfailedtomatchanyof['AfdRestart']Decompiling34functionsusing8threads
Setup8decompliers
Decompiled34functionsforafd.sys.10.0.22621.1415in0.86437463760375980decompilationsalreadyexisted.
Wrote34decompilationsforafd.sys.10.0.22621.1415todecompilations/afd.sys.10.0.22621.1415in0.0516660213470459

Error:timeexpiredforAfdLRRepostReceivefunc:AfdRestartBufferSend.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN

Error:timeexpiredforAfdReuseConnectionfunc:AfdRestartDeviceControl.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN

Error:timeexpiredforAfdConnectfunc:AfdRestartSend.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN

Error:timeexpiredforWskProControlSocketCorefunc:AfdRestartAbort.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN

Error:timeexpiredforWskProIRPControlSocketfunc:AfdRestartDelayedAcceptListen.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN

Error:timeexpiredforAfdSanAcceptCorefunc:AfdRestartDisconnect.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN

Error:timeexpiredforAfdTPacketsBufferReadfunc:AfdRestartMdlReadComplete.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN

Error:timeexpiredforAfdSanAcceptCorefunc:AfdRestartTPDetachedSend.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN

Error:timeexpiredforAfdTLBindSecurityCompletefunc:AfdRestartTPacketsBufferRead.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN

Error:timeexpiredforFUN_1c0023892func:AfdRestartTPacketsMdlRead.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN

Error:timeexpiredforWskProIRPControlSocketfunc:AfdRestartTPacketsSend.max_run_time:5Increasetimeoutwith--max-time-cg-genMAX_TIME_CG_GEN
Callgraphed34functionsforafd.sys.10.0.22621.1415in10.055054426193237
Wrote34callgraphsforafd.sys.10.0.22621.1415todecompilations/afd.sys.10.0.22621.1415/callgraphsin10.0551524162292480callgraphsalreadyexisted.Sample Calling Callgraph Output AfdRestartDgConnect:flowchart TD
classDef sh fill:#339933
0["AfdRestartBufferReceiveWithUserIrp"] --> 1["AfdLRRepostReceive"]
0 --> 2["AfdTLPostPendedReceives"]
3["AfdRestartSuperAccept"] --> 4["AfdContinueSuperAccept"]
5["AfdRestartAccept"] --> 6["AfdServiceSuperAccept"]
7["AfdIssueDeviceControl"] --> 8["AfdRestartDeviceControl"]
9["AfdBCommonChainedReceiveEventHandler"] --> 0
9 --> 10["AfdCommonRestartBufferReceive"]
9 --> 11["FUN_1c0008952"]
12["AfdTLConnectedReceiveEventHandler"]:::sh --> 9
13["AfdBChainedReceiveEventHandler"] --> 9
14["AfdTdiSetEventHandlers"] --> 13
14 --> 15["AfdBReceiveExpeditedEventHandler"]
14 --> 16["AfdBReceiveEventHandler"]
17["AfdRestartBufferReceive"] --> 10
18["AfdBind"]:::sh --> 14
18:::sh --> 19["AfdCreateConnection"]
18:::sh --> 20["AfdTLBindSecurity"]
18:::sh --> 21["AfdRestartBindGetAddress"]
22["AfdRestartSend"] --> 22
23["AfdTLSendComplete"] --> 22
24["AfdTLStartVcSend"] --> 23
25["AfdTLConnectEventHandler"]:::sh --> 3
25:::sh --> 26["AfdTLDelayedAcceptCompletion"]
25:::sh --> 5
16 --> 0
16 --> 1
16 --> 17
27["AfdAccept"]:::sh --> 28["AfdRestartDelayedAccept"]
27:::sh --> 29["AfdTLCancelResumeDelayAccept"] 
26 --> 28
26 --> 30["AfdRestartDelayedSuperAccept"]
15 --> 16
31["AfdTLCompleteBufferUserReceive"] --> 0
32["AfdTLPostUserReceive"] --> 31
2 --> 32
10 --> 2
10 --> 1
19 --> 7
33["AfdBPostDrainReceive"] --> 17
33 --> 34["AfdTLCompleteBufferReceive"]
33 --> 10
35["AfdRestartSuperConnect"] --> 36["AfdRestartBufferSend"]
37["AfdConnectEventHandler"] --> 3
37 --> 5
38["FUN_1c000e1aa"] --> 19
38 --> 39["AfdDoDatagramConnect"]
40["AfdSendQueuedTPSend"] --> 24
40 --> 41["AfdTLBufferedSendComplete"]
42["AfdConnect"]:::sh --> 38
43["AfdSuperConnect"]:::sh --> 35
43:::sh --> 41
44["AfdTLAbortEventHandler"]:::sh --> 26
29 --> 26
1 --> 33
1 --> 0
45["AfdCompleteTPackets"] --> 40
45 --> 46["AfdTPacketsWorker"]
45 --> 47["AfdStartNextQueuedTransmit"]
48["FUN_1c0027fa2"] --> 19
49["FUN_1c0021418"] --> 36
49 --> 41
50["AfdFastConnectionSend"] --> 49
51["AfdBInitDrainBytesInTransport"] --> 1
52["FUN_1c002246f"] --> 51
52 --> 53["FUN_1c0004001"]
54["FUN_1c002ed68"] --> 29
54 --> 30
54 --> 54
54 --> 55["AfdRestartSuperAcceptListen"]
56["FUN_1c002d729"] --> 37
57["AfdTLBindComplete2"] --> 48
58["AfdRestartTPacketsMdlRead"] --> 45
58 --> 46
58 --> 59["AfdTPacketsContinueAfterRead"]
60["AfdTLDgramBindComplete"] --> 57
61["AfdFastIoDeviceControl"]:::sh --> 50
62["AfdTLBindComplete"] --> 60
62 --> 63["FUN_1c0027f76"]
62 --> 57
64["AfdTLBind"] --> 62
65["AfdTLBindSecurityComplete"] --> 64
65 --> 20
65 --> 57
20 --> 65
20 --> 64
63 --> 60
66["AfdBReceive"] --> 52
66 --> 67["FUN_1c0022408"]
68["AfdStartListen"]:::sh --> 56
69["AfdTPacketsMdlRead"] --> 58
69 --> 59
30 --> 4
6 --> 54
70["AfdFastIoWrite"]:::sh --> 50
41 --> 36
71["FUN_1c002ec66"] --> 6
71 --> 71
71 --> 72["AfdCloseConnection"]
46 --> 69
46 --> 46
46 --> 73["AfdTPacketsSend"]
46 --> 74["AfdTPacketsBufferRead"]
46 --> 75["AfdStartNextTPacketsIrp"]
76["AfdRestartSuperAcceptGetAddress"] --> 4
34 --> 10
4 --> 76
4 --> 77["AfdRestartSuperAcceptReceive"]
55 --> 4
78["AfdReceive"] --> 66
79["AfdCommonRestartTPacketsSend"] --> 46
79 --> 73
80["AfdTLRestartTPacketsSend"] --> 79
81["AfdTLTPacketsSend"] --> 80
82["AfdDispatch"] --> 78
83["DriverEntry"] --> 82
73 --> 81
73 --> 84["AfdRestartTPacketsSend"]
73 --> 75
85["AfdSanConnectHandler"]:::sh --> 6
86["FUN_1c00128c9"] --> 6
87["AfdSuperAccept"]:::sh --> 86
88["entry"]:::sh --> 83
59 --> 73
74 --> 59
74 --> 89["AfdRestartTPacketsBufferRead"]
89 --> 59
89 --> 46
90["FUN_1c0023892"] --> 51
90 --> 90
90 --> 33
91["AfdGetAddress"]:::sh --> 92["AfdRestartGetAddress"]
84 --> 79
75 --> 46
47 --> 46
93["AfdCompleteClosePendedTPackets"] --> 47
11 --> 1
94["AfdFreeNPConnectionResources"] --> 93
95["AfdFreeConnectionResources"] --> 94
96["AfdFreeConnectionEx"] --> 95
72 --> 96
97["AfdReturnNicsPackets"]:::sh --> 72
53 --> 32
67 --> 33
39 --> 98["AfdRestartDgConnect"]Sample MindMap Output for AfdRestartDgConnectmindmap
root((AfdRestartDgConnect))
      AfdBCommonChainedReceiveEventHandler
        AfdBChainedReceiveEventHandler
      AfdTLSendComplete
      AfdBReceiveEventHandler
        AfdBReceiveExpeditedEventHandler
      AfdBReceiveEventHandler
        AfdTdiSetEventHandlers
      AfdTLCompleteBufferUserReceive
        AfdTLPostUserReceive
      AfdIssueDeviceControl
      AfdTLDelayedAcceptCompletion
        AfdCreateConnection
        AfdTLStartVcSend
      AfdRestartSuperConnect
      AfdTLDelayedAcceptCompletion
      AfdBPostDrainReceive
        AfdCreateConnection
      FUN_1c0021418
        AfdLRRepostReceive
        AfdTLCancelResumeDelayAccept
      AfdConnectEventHandler
        AfdFastConnectionSend
        FUN_1c002d729
      FUN_1c002ed68
        FUN_1c002d729
      AfdTLBufferedSendComplete
        FUN_1c0021418
        AfdServiceSuperAccept
      AfdContinueSuperAccept
        AfdServiceSuperAccept
      AfdTLBufferedSendComplete
        AfdSendQueuedTPSend
        AfdTLCancelResumeDelayAccept
        AfdServiceSuperAcceptExample BSim signature generationUseghidrecompto generate Ghidra BSim compatible feature vectors. These XMLs can later be added to a BSim database.Command lineghidrecomp--bsim--bsim-catnewcat:newvalOutput(.env)vscode➜/workspaces/ghidrecomp(bsim)$ghidrecomp--bsim--bsim-catnewcat:newval/bin/ls
Startingdecompliations:Namespace(bin='/bin/ls',cppexport=False,filters=None,project_path='ghidra_projects',gdt=None,output_path='ghidrecomps',skip_cache=False,sym_file_path=None,symbols_path='symbols',skip_symbols=False,thread_count=12,va=False,fa=False,max_ram_percent=50.0,print_flags=False,callgraphs=False,callgraph_filter='.',max_display_depth=None,max_time_cg_gen=5,cg_direction='calling',bsim=True,bsim_sig_path='bsim-xmls',bsim_template='medium_nosize',bsim_cat=['newcat:newval'])INFOUsinglogconfigfile:jar:file:/ghidra/Ghidra/Framework/Generic/lib/Generic.jar!/generic.log4j.xml(LoggingInitialization)INFOUsinglogfile:/home/vscode/.ghidra/.ghidra_11.0_PUBLIC/application.log(LoggingInitialization)INFOLoadinguserpreferences:/home/vscode/.ghidra/.ghidra_11.0_PUBLIC/preferences(Preferences)INFOSearchingforclasses...(ClassSearcher)INFOClasssearchcomplete(660ms)(ClassSearcher)<severallinesomitted>
Decompiled566functionsforlsin2.43738842010498050decompilationsalreadyexisted.
Wrote566decompilationsforlstoghidrecomps/ls/decompsin0.16666936874389648
GeneratingBSimsigsfor566functionsforls
Addingcategorytype:newcatval:newval
Categoriesadded:[('newcat','newval')]GeneratedBSimsigsfor451functionsin1.248070478439331
Sigsareinghidrecomps/bsim-xmls/sigs_35d820f0762118215cbe19fb44e612ca_lsFiles generated$treeghidrecomps
ghidrecomps/
├──bsim-xmls
│├──sigs_35d820f0762118215cbe19fb44e612ca_ls
│├──sigs_b4c4b6ef5980df8440fb26daffb4118f_afd.sys.10.0.22621.1415
│└──sigs_fffefca59f1dcb04e318b6b26fa1b50e_ls_aarch64
├──ghidra_projects
│├──ls
││└──ls.rep
├──ls
│└──decompsInstallationDownloadandinstall GhidraandJavarequired for Ghidra.Set Ghidra Environment VariableGHIDRA_INSTALL_DIRto Ghidra install location.Pip installghidrecompWindowsPSC:\Users\user>[System.Environment]::SetEnvironmentVariable('GHIDRA_INSTALL_DIR','C:\ghidra_10.2.3_PUBLIC_20230208\ghidra_10.2.3_PUBLIC')PSC:\Users\user>pipinstallghidrecompLinux / MacexportGHIDRA_INSTALL_DIR="/path/to/ghidra/"pipinstallghidrecompDevcontainer / DockerAvoid installing Ghidra and Java on your host by using adevcontainer.Option 1 - DevcontainerUse the.devcontainerin this repo. Click the above button if you have VS code installed. If this concept is new to you, check out :ghidra-python-vscode-devcontainer-skeleton quick setupwhich explains a bit more about dev containers.Option 2 - DockerUse the published repo image with Ghidra and Java already installed.dockerpullghcr.io/clearbluejar/ghidrecomp:latest
dockerrun--uservscode--rm-itghcr.io/clearbluejar/ghidrecomp:latestbashFrom within the image:vscode➜/$uname-a
Linux4da2fe33369a5.15.49-linuxkit#1 SMP PREEMPT Tue Sep 13 07:51:32 UTC 2022 x86_64 GNU/Linuxvscode➜/$ls/ghidra/
ExtensionsGPLGhidraLICENSEbom.jsondocsghidraRunghidraRun.batlicensesserversupport
vscode➜/$pipinstallghidrecomp
SuccessfullyinstalledJpype1-1.4.1ghidrecomp-0.1.0packaging-23.0pyhidra-0.4.1