### Install bindiff_config_setup Executable Source: https://github.com/google/bindiff/blob/main/tools/CMakeLists.txt Installs the bindiff_config_setup executable to the 'bindiff-prefix' directory at runtime. ```cmake install(TARGETS bindiff_config_setup RUNTIME DESTINATION bindiff-prefix) ``` -------------------------------- ### Build and Install BinDiff Source: https://github.com/google/bindiff/blob/main/README.md Invoke the actual build process using CMake and Ninja. This step compiles the code and places binaries in the specified installation directory. It also runs tests. ```bash cmake --build build/out --config Release (cd build/out; ctest --build-config Release --output-on-failure) cmake --install build/out --config Release ``` -------------------------------- ### FindString Usage Example Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-fixed-points.md Demonstrates how to use FindString to get an interned string and set it as a matching step. ```cpp const std::string* algo_name = FindString("call_graph_edges"); match.SetMatchingStep(*algo_name); ``` -------------------------------- ### ChangeType Usage Example Source: https://github.com/google/bindiff/blob/main/_autodocs/types.md Demonstrates how to check for specific change types using bitwise operations and how to get a descriptive string for the flags. ```cpp if (fixed_point.HasFlag(CHANGE_STRUCTURAL)) { // Function structure was modified } std::string desc = GetChangeDescription(fixed_point.GetFlags()); // Returns string like "G-I-----" for structural and instruction changes ``` -------------------------------- ### Algorithm-Specific Settings Example Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md This JSON object shows an example of algorithm-specific settings that can be included in a BinDiff configuration. It demonstrates parameters like minimum similarity, maximum distance, and operand usage. ```json { "name": "custom_algorithm", "enabled": true, "settings": { "min_similarity": 0.5, "max_distance": 100, "use_operands": true, "invert_result": false } } ``` -------------------------------- ### Full Classification Workflow Example Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-change-classifier.md A comprehensive example showing the integration of diffing and classification within an analysis function. It includes context creation, running diff algorithms, classifying changes, and reporting a summary. ```cpp #include "change_classifier.h" #include "differ.h" void AnalyzeChanges(const CallGraph& cg1, const CallGraph& cg2, const FlowGraphs& fg1, const FlowGraphs& fg2, FixedPoints& fixed_points) { // Create context MatchingContext context(cg1, cg2, fg1, fg2, fixed_points); // Run diffing MatchingSteps call_steps = LoadCallGraphAlgorithms(); MatchingStepsFlowGraph bb_steps = LoadBasicBlockAlgorithms(); Diff(&context, call_steps, bb_steps); // Classify changes ClassifyChanges(&context); // Report results LOG(INFO) << "=== Change Analysis ==="; LOG(INFO) << "Found " << context.fixed_points_.size() << " matches"; LOG(INFO) << ""; int structural_changes = 0; int instruction_changes = 0; int identical = 0; for (const auto& match : context.fixed_points_) { std::string changes = GetChangeDescription(match.GetFlags()); if (match.GetFlags() == CHANGE_NONE) { identical++; } else if (match.HasFlag(CHANGE_STRUCTURAL)) { structural_changes++; } else if (match.HasFlag(CHANGE_INSTRUCTIONS)) { instruction_changes++; } if (match.GetFlags() != CHANGE_NONE) { LOG(INFO) << "0x" << std::hex << match.GetPrimary()->GetEntryPointAddress() << ": " << changes; } } LOG(INFO) << ""; LOG(INFO) << "Summary:"; LOG(INFO) << " Identical: " << identical; LOG(INFO) << " Structural changes: " << structural_changes; LOG(INFO) << " Instruction changes: " << instruction_changes; } ``` -------------------------------- ### Install IDA Plugin Source: https://github.com/google/bindiff/blob/main/ida/CMakeLists.txt Installs the built IDA plugin to the specified destination. ```cmake ida_install(TARGETS ${bindiff_ida_plugin_name} ARCHIVE DESTINATION bindiff-prefix RUNTIME DESTINATION bindiff-prefix LIBRARY DESTINATION bindiff-prefix) ``` -------------------------------- ### Install macOS Launcher Executable (Conditional) Source: https://github.com/google/bindiff/blob/main/tools/CMakeLists.txt Installs the bindiff_launcher_macos executable to the 'bindiff-prefix' directory at runtime, but only if the target is macOS. ```cmake install(TARGETS bindiff_launcher_macos RUNTIME DESTINATION bindiff-prefix) ``` -------------------------------- ### Example bindiff.json Structure Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Illustrates the JSON structure for configuring BinDiff algorithms. ```json { "call_graph_algorithms": [ { "name": "call_graph_edges", "enabled": true, "settings": {} }, { "name": "call_graph_prime", "enabled": true, "settings": {} } ], "basic_block_algorithms": [ { "name": "basic_block_prime", "enabled": true, "settings": {} }, { "name": "basic_block_edges", "enabled": true, "settings": {} } ] } ``` -------------------------------- ### Complete BinDiff Workflow Example Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-differ.md Illustrates the end-to-end process of loading binaries, setting up the matching context, running the diff algorithm, analyzing results, and cleaning up resources. ```cpp // Load two binaries CallGraph call_graph1, call_graph2; FlowGraphs flow_graphs1, flow_graphs2; Instruction::Cache cache; absl::Status status1 = Read("binary1.binexport", &call_graph1, &flow_graphs1, nullptr, &cache); absl::Status status2 = Read("binary2.binexport", &call_graph2, &flow_graphs2, nullptr, &cache); if (!status1.ok() || !status2.ok()) { LOG(ERROR) << "Failed to load binaries"; return; } // Create matching context FixedPoints fixed_points; MatchingContext context(call_graph1, call_graph2, flow_graphs1, flow_graphs2, fixed_points); // Load matching algorithms (typically from config) MatchingSteps call_steps = LoadCallGraphAlgorithms(); MatchingStepsFlowGraph bb_steps = LoadBasicBlockAlgorithms(); // Run the diff algorithm Diff(&context, call_steps, bb_steps); // Analyze results Histogram histogram; Counts counts; GetCountsAndHistogram(flow_graphs1, flow_graphs2, fixed_points, &histogram, &counts); double similarity = GetSimilarityScore(call_graph1, call_graph2, histogram, counts); LOG(INFO) << "Binary similarity: " << similarity; // Cleanup ScopedCleanup cleanup(&flow_graphs1, &flow_graphs2, &cache); ``` -------------------------------- ### Get Entry Point Address Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-flow-graph.md Retrieves the starting address of the function represented by the flow graph. This operation has a constant time complexity. ```cpp Address entry = flow_graph.GetEntryPointAddress(); ``` -------------------------------- ### Define bindiff_config_setup Executable Source: https://github.com/google/bindiff/blob/main/tools/CMakeLists.txt Defines the main configuration setup executable for BinDiff. This executable is built from config_setup.cc. ```cmake add_executable(bindiff_config_setup config_setup.cc) ``` -------------------------------- ### Example Usage: Creating and Managing Function-Level Matches Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-fixed-points.md Illustrates the process of creating a function-level match, adding basic block matches, marking changes, and storing the match in a collection. ```cpp // Create a function-level match FixedPoint func_match(&flow_graph1, &flow_graph2, "call_graph_prime"); func_match.SetConfidence(0.92); func_match.SetSimilarity(0.88); // Add basic block matches to the function match for (size_t i = 0; i < num_matched_blocks; ++i) { auto bb_vertex1 = flow_graph1.GetVertex(addresses1[i]); auto bb_vertex2 = flow_graph2.GetVertex(addresses2[i]); if (bb_vertex1 != std::numeric_limits::max() && bb_vertex2 != std::numeric_limits::max()) { func_match.Add(bb_vertex1, bb_vertex2, "basic_block_hash"); } } // Mark changes if (func_match.GetBasicBlockFixedPoints().size() < func_match.GetPrimary()->GetBasicBlockCount()) { func_match.SetFlag(CHANGE_STRUCTURAL); } // Store in collection FixedPoints all_matches; all_matches.insert(func_match); ``` -------------------------------- ### Get Database Filename Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-database-writer.md Returns the file path of the currently opened database. ```cpp const std::string& GetFilename() const ``` -------------------------------- ### Layered Configuration Loading Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Shows how to load and merge configurations from multiple sources, starting with defaults and layering system, user, and project settings. ```cpp // Start with hardcoded defaults Config config = config::Defaults(); // Apply system-wide settings auto sys_result = config::LoadFromFile("/etc/bindiff.json"); if (sys_result.ok()) { config::MergeInto(std::move(sys_result).value(), config); } // Apply user settings auto user_result = config::LoadFromFile(GetUserConfigPath()); if (user_result.ok()) { config::MergeInto(std::move(user_result).value(), config); } // Apply project settings auto proj_result = config::LoadFromFile("./bindiff.json"); if (proj_result.ok()) { config::MergeInto(std::move(proj_result).value(), config); } // config now has layered settings from all sources ``` -------------------------------- ### ResetMatches Example Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-differ.md Shows how to reset matches on two sets of flow graphs after an initial diff, preparing them for new comparisons. ```cpp // After first diffing ResetMatches(&flow_graphs1); ResetMatches(&flow_graphs2); // Now flow_graphs can be matched against different binaries ``` -------------------------------- ### Load and Diff Two Binaries Source: https://github.com/google/bindiff/blob/main/_autodocs/INDEX.md This snippet demonstrates the setup, loading of binary export data, and the core diffing process using BinDiff's API. Ensure necessary algorithms are loaded before calling Diff. ```cpp // Setup CallGraph cg1, cg2; FlowGraphs fg1, fg2; Instruction::Cache cache; // Load Read("bin1.binexport", &cg1, &fg1, nullptr, &cache); Read("bin2.binexport", &cg2, &fg2, nullptr, &cache); // Diff FixedPoints fps; MatchingContext ctx(cg1, cg2, fg1, fg2, fps); MatchingSteps call_steps = LoadCallGraphAlgorithms(); MatchingStepsFlowGraph bb_steps = LoadBasicBlockAlgorithms(); Diff(&ctx, call_steps, bb_steps); // Results in fps ``` -------------------------------- ### Get BinDiff Data Directory Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Retrieves the BinDiff data directory from configuration. Uses a default if not specified. ```cpp std::string GetBinDiffDirOrDefault(const Config& from) ``` ```cpp Config config = config::Proto(); std::string data_dir = config::GetBinDiffDirOrDefault(config); LOG(INFO) << "BinDiff directory: " << data_dir; ``` -------------------------------- ### Complete BinDiff Analysis Example Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-statistics.md Demonstrates a full analysis workflow, including creating statistics, calculating similarity and confidence scores, and displaying detailed results. This snippet requires several BinDiff headers and objects. ```cpp #include "third_party/zynamics/bindiff/statistics.h" #include "third_party/zynamics/bindiff/differ.h" void AnalyzeDiff(const CallGraph& cg1, const CallGraph& cg2, const FlowGraphs& fg1, const FlowGraphs& fg2, const FixedPoints& fps) { // Create statistics Counts counts; Histogram histogram; // Populate from comparison GetCountsAndHistogram(fg1, fg2, fps, &histogram, &counts); // Calculate scores double similarity = GetSimilarityScore(cg1, cg2, histogram, counts); Confidences confidences; double confidence = GetConfidence(histogram, &confidences); // Display results LOG(INFO) << "=== BinDiff Analysis Results ==="; LOG(INFO) << "Similarity: " << std::fixed << std::setprecision(2) << (similarity * 100) << "%\n"; LOG(INFO) << "Confidence: " << std::fixed << std::setprecision(2) << (confidence * 100) << "%\n"; LOG(INFO) << ""; // Display statistics LOG(INFO) << "=== Statistics ==="; for (int i = 0; i < Counts::ui_entry_size(); ++i) { auto [name, value] = counts.GetEntry(i); if (!name.empty()) { LOG(INFO) << name << ": " << value; } } // Algorithm breakdown LOG(INFO) << ""; LOG(INFO) << "=== Algorithm Contributions ==="; for (const auto& [algo_name, count] : histogram) { LOG(INFO) << algo_name << ": " << count << " matches"; } } ``` -------------------------------- ### filename Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-database-writer.md Alternative method to get the database file path. ```APIDOC ## filename ### Description Alternative method to get the database file path. ### Returns `const std::string&` - File path. ``` -------------------------------- ### DeleteFlowGraphs Example Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-differ.md Demonstrates how to use the DeleteFlowGraphs function to clear a FlowGraphs container. ```cpp FlowGraphs flow_graphs; // ... populate and use ... DeleteFlowGraphs(&flow_graphs); ``` -------------------------------- ### Custom Reader Implementation Example Source: https://github.com/google/bindiff/blob/main/_autodocs/INDEX.md Shows the basic structure for implementing a custom reader by inheriting from the Reader base class. The Read method must be overridden. ```cpp class CustomReader : public Reader { absl::Status Read(CallGraph&, CallGraph&, FlowGraphInfos&, FlowGraphInfos&, FixedPointInfos&) override { ... } }; ``` -------------------------------- ### Configure BinDiff Build with CMake Source: https://github.com/google/bindiff/blob/main/README.md Configure the build directory and generate build files using CMake. Specify the build type, installation prefix, and paths to BinExport and IDA SDK. ```bash cmake -S . -B build/out -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=build/out \ -DBINDIFF_BINEXPORT_DIR=build/binexport \ "-DIdaSdk_ROOT_DIR=${PWD}build/idasdk" ``` -------------------------------- ### Populating Counts from Flow Graphs Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-statistics.md Provides an example of how to populate the Counts object by processing flow graphs and fixed points. It shows counting basic blocks, edges, instructions, and matched elements. ```cpp Counts counts; // Count all basic blocks, edges, and instructions Count(flow_graphs1, &counts); Count(flow_graphs2, &counts); // Count matched elements for (const auto& fixed_point : fixed_points) { Count(fixed_point, &counts, &histogram); } ``` -------------------------------- ### Get and Set Matching Step Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-fixed-points.md Retrieves or sets the name of the matching algorithm used to generate a match. Use this to track the origin of a match. ```cpp const std::string& GetMatchingStep() const void SetMatchingStep(const std::string& matching_step) ``` ```cpp match.SetMatchingStep("call_graph_edges"); std::string algo = match.GetMatchingStep(); ``` -------------------------------- ### Get Default BinDiff Configuration Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Retrieves the hardcoded default BinDiff configuration without loading from the filesystem. Useful for inspecting default settings. ```cpp const auto& defaults = config::Defaults(); LOG(INFO) << "Default algorithms count: " << defaults.call_graph_algorithms_size(); ``` -------------------------------- ### Get and Set Executable Hash Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-call-graph.md Manages the hash of the original input binary. Use SetExeHash to store a checksum for integrity verification. ```cpp const std::string& GetExeHash() const void SetExeHash(std::string hash) ``` -------------------------------- ### Get Global BinDiff Configuration Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Retrieves the current global BinDiff configuration. Initializes from filesystem locations on first call, falling back to defaults if none are found. ```cpp Config& config = config::Proto(); // Modify global configuration ``` -------------------------------- ### Create and Modify BinDiff Configuration Programmatically Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md This C++ function shows how to create a BinDiff configuration programmatically, starting from default settings. It demonstrates clearing existing algorithms and adding custom ones, then saving the modified configuration. ```cpp // Option 3: Programmatic configuration void CreateProgrammatically() { Config config = config::Defaults(); // Modify as needed config.mutable_call_graph_algorithms()->Clear(); // Add custom algorithms... // Save for next run config::SaveUserConfig(config); } ``` -------------------------------- ### Getting UI Entry Size Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-statistics.md Shows how to determine the number of statistics intended for user interface display using the ui_entry_size() static method. This helps in differentiating between UI and internal statistics. ```cpp for (size_t i = 0; i < Counts::ui_entry_size(); ++i) { // These entries are shown in the UI } for (size_t i = Counts::ui_entry_size(); i < Counts::kNumCountEntries; ++i) { // These entries are internal only } ``` -------------------------------- ### Typical BinDiff Workflow Source: https://github.com/google/bindiff/blob/main/_autodocs/INDEX.md This snippet demonstrates the typical workflow for using BinDiff to compare two binaries. It covers loading binaries, creating a comparison context, running matching algorithms, analyzing results, and writing the output to a database. ```cpp // 1. Load two binaries CallGraph cg1, cg2; FlowGraphs fg1, fg2; Instruction::Cache cache; Read("binary1.binexport", &cg1, &fg1, nullptr, &cache); Read("binary2.binexport", &cg2, &fg2, nullptr, &cache); // 2. Create comparison context FixedPoints fps; MatchingContext ctx(cg1, cg2, fg1, fg2, fps); // 3. Run matching algorithms Diff(&ctx, call_graph_steps, basic_block_steps); // 4. Analyze and classify results ClassifyChanges(&ctx); GetCountsAndHistogram(fg1, fg2, fps, &histogram, &counts); // 5. Write results to database auto writer = DatabaseWriter::Create("results.bd").value(); writer->Write(cg1, cg2, fg1, fg2, fps); ``` -------------------------------- ### Typical BinDiff Workflow Source: https://github.com/google/bindiff/blob/main/_autodocs/README.md Illustrates the sequential steps for performing a binary diff analysis using BinDiff, from loading binaries to persisting results. ```text 1. Load Binaries └─→ Read("binary1.binexport", ...) └─→ Read("binary2.binexport", ...) 2. Create Comparison Context └─→ MatchingContext(cg1, cg2, fg1, fg2, fps) 3. Run Matching Algorithm └─→ Diff(&context, call_steps, basic_block_steps) 4. Analyze Changes └─→ ClassifyChanges(&context) 5. Calculate Statistics └─→ GetCountsAndHistogram(fg1, fg2, fps, &hist, &counts) 6. Assess Quality └─→ GetSimilarityScore(cg1, cg2, hist, counts) └─→ GetConfidence(hist, nullptr) 7. Persist Results └─→ DatabaseWriter::Create("results.bd", options) └─→ writer->Write(cg1, cg2, fg1, fg2, fps) ``` -------------------------------- ### Get Vertex by Address Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-flow-graph.md Performs a binary search to find the basic block (vertex) starting at a specific address. Returns an invalid vertex if not found. ```cpp FlowGraph::Vertex bb = flow_graph.GetVertex(0x401050); if (bb != std::numeric_limits::max()) { // Process basic block } ``` -------------------------------- ### Run Core Matching Algorithm Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-differ.md Use the Diff function as the main entry point to initiate the binary diffing process. It requires a MatchingContext and lists of matching steps for call graph and basic block levels. ```cpp void Diff(MatchingContext* absl_nonnull context, const MatchingSteps& call_graph_steps, const MatchingStepsFlowGraph& basic_block_steps) ``` ```cpp MatchingContext context(call_graph1, call_graph2, flow_graphs1, flow_graphs2, fixed_points); // Set up matching steps (typically loaded from configuration) MatchingSteps call_graph_steps = CreateCallGraphSteps(); MatchingStepsFlowGraph basic_block_steps = CreateBasicBlockSteps(); // Run the diffing algorithm Diff(&context, call_graph_steps, basic_block_steps); // Results are in context.fixed_points_ ``` -------------------------------- ### Manage Flags for Basic Blocks and Edges Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-flow-graph.md Provides functions to get and set flags for basic blocks and edges. Includes constants for different flag types like unconditional edges and loop entries. ```cpp uint32_t GetFlags(Vertex vertex) const void SetFlags(Vertex vertex, uint32_t flags) uint8_t GetFlags(const Edge& edge) const void SetFlags(const Edge& edge, uint8_t flags) ``` ```cpp uint32_t bb_flags = flow_graph.GetFlags(vertex); if (bb_flags & FlowGraph::VERTEX_LOOPENTRY) { // This is a loop entry } uint8_t edge_type = flow_graph.GetFlags(edge); ``` -------------------------------- ### Configuration Loading Workflow Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Demonstrates various methods for loading BinDiff configurations, including global, file-based, and JSON string loading, as well as merging and saving. ```cpp // 1. Use global configuration (auto-loaded on first call) Config& config = config::Proto(); // 2. Or load custom configuration from file auto result = config::LoadFromFile("custom.json"); if (result.ok()) { Config custom_config = std::move(result).value(); // Use custom_config } // 3. Or load from JSON string std::string json = ReadConfigFile(); auto parse_result = config::LoadFromJson(json); if (parse_result.ok()) { Config config = std::move(parse_result).value(); // Use config } // 4. Merge configurations Config defaults = config::Defaults(); config::MergeInto(custom_config, defaults); // defaults now has custom settings // 5. Save user modifications config::SaveUserConfig(defaults); ``` -------------------------------- ### Populate Matching Steps with Configuration Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md This C++ code illustrates how to use a BinDiff configuration object to create matching steps for call graphs and flow graphs. These steps are then passed to the differ for analysis. ```cpp // Configuration is used to populate matching steps: MatchingSteps CreateCallGraphSteps(const Config& config); MatchingStepsFlowGraph CreateBasicBlockSteps(const Config& config); // Then passed to the differ: Diff(&context, call_graph_steps, basic_block_steps); ``` -------------------------------- ### Proto() Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Returns the current global BinDiff configuration. Initializes from filesystem locations on first call or uses defaults if none are found. ```APIDOC ## Proto() ### Description Returns the current global BinDiff configuration. On first call, initializes from well-known filesystem locations. If no configuration is found, uses default values. ### Returns `Config&` - Mutable reference to global configuration. ### Example ```cpp Config& config = config::Proto(); // Modify global configuration ``` ``` -------------------------------- ### Get Prime Signature Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-flow-graph.md Returns the instruction prime product (signature) for a basic block or function. The prime is computed from instruction mnemonics according to the BinExport protocol. Use the vertex parameter for a specific basic block. ```cpp uint64_t bb_prime = flow_graph.GetPrime(vertex); uint64_t func_prime = flow_graph.GetPrime(); ``` -------------------------------- ### Load Custom BinDiff Configuration from File Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md This C++ function demonstrates loading a custom BinDiff configuration from a specified file. It includes error handling for the loading process and suggests using the loaded configuration for matching algorithms. ```cpp // Option 2: Load custom configuration void UseCustomConfig(const std::string& filename) { auto result = config::LoadFromFile(filename); if (!result.ok()) { LOG(ERROR) << "Config error: " << result.status(); return; } Config config = std::move(result).value(); // Use config for matching algorithms } ``` -------------------------------- ### Get Instruction Address Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-instruction.md Retrieves the memory address of the instruction. ```cpp Address addr = insn.GetAddress(); LOG(INFO) << "Instruction at 0x" << std::hex << addr; ``` -------------------------------- ### BasicBlockFixedPoint::GetMatchingStep / SetMatchingStep Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-fixed-points.md Gets or sets the name of the algorithm that identified this basic block match. ```APIDOC ## BasicBlockFixedPoint::GetMatchingStep / SetMatchingStep ### Description Gets or sets the name of the matching algorithm that found this match. ### Method GET / SET ### Endpoint BasicBlockFixedPoint::GetMatchingStep() BasicBlockFixedPoint::SetMatchingStep(const std::string& matching_step) ### Parameters #### Path Parameters - **matching_step** (`const std::string&`) - Required - Algorithm name (e.g., "basic_block_prime", "basic_block_hash") (Setter only) ### Response #### Success Response (200) - **GetMatchingStep** (`const std::string&`) - Algorithm name. ### Request Example ```cpp std::string algo = bb_match.GetMatchingStep(); LOG(INFO) << "Match found by: " << algo; bb_match.SetMatchingStep("manual_match"); ``` ### Response Example ```json { "example": "basic_block_prime" } ``` ``` -------------------------------- ### Create Instruction Object Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-instruction.md Demonstrates how to create an Instruction object, providing a cache, address, mnemonic, and prime signature. ```cpp Instruction::Cache cache; Instruction insn(&cache, 0x401000, "mov", 17); // 17 is prime for "mov" ``` -------------------------------- ### CallGraph::GetFilePath Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-call-graph.md Gets the fully specified filename including path and extension as it was passed to the Read() method. ```APIDOC ## CallGraph::GetFilePath ### Description Gets the fully specified filename including path and extension as passed to `Read()`. ### Method `CallGraph::GetFilePath` ### Returns `std::string` - Complete path and filename. ### Source `call_graph.h:98` ``` -------------------------------- ### SetSimilarity / GetSimilarity Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-fixed-points.md Sets or gets the similarity score for this match. The similarity score ranges from 0.0 to 1.0. ```APIDOC ## SetSimilarity / GetSimilarity ### Description Sets or gets the similarity score for this match (0.0 to 1.0). ### Method GET (GetSimilarity), SET (SetSimilarity) ### Parameters #### Setter Parameters - `similarity` (double) - Required - Similarity value ### Returns - `double` - Similarity score. ### Example ```cpp match.SetSimilarity(0.85); double sim = match.GetSimilarity(); ``` ``` -------------------------------- ### SetConfidence / GetConfidence Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-fixed-points.md Sets or gets the confidence score for this match. The confidence score ranges from 0.0 to 1.0. ```APIDOC ## SetConfidence / GetConfidence ### Description Sets or gets the confidence score for this match (0.0 to 1.0). ### Method GET (GetConfidence), SET (SetConfidence) ### Parameters #### Setter Parameters - `confidence` (double) - Required - Confidence value (typically 0.0-1.0) ### Returns - `double` - Confidence score. ### Example ```cpp match.SetConfidence(0.95); double conf = match.GetConfidence(); if (conf > 0.8) { LOG(INFO) << "High confidence match"; } ``` ``` -------------------------------- ### Load BinDiff Configuration from File Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Loads BinDiff configuration from a specified file path. Returns an error status if the file cannot be loaded or parsed. ```cpp auto result = config::LoadFromFile("/etc/bindiff/bindiff.json"); if (!result.ok()) { LOG(ERROR) << "Failed to load config: " << result.status(); return; } Config config = std::move(result).value(); ``` -------------------------------- ### Link Libraries for bindiff_config_setup Source: https://github.com/google/bindiff/blob/main/tools/CMakeLists.txt Links the necessary libraries for the bindiff_config_setup executable. This includes Abseil libraries, BinDiff internal libraries, andbinexport_shared. ```cmake target_link_libraries(bindiff_config_setup absl::flags_parse absl::str_format absl::status absl::statusor absl::strings bindiff_config bindiff_version binexport_shared bindiff_base ) ``` -------------------------------- ### CallGraph::GetFilename Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-call-graph.md Gets just the filename part (without path or extension) from the filename that was previously passed to the Read() method. ```APIDOC ## CallGraph::GetFilename ### Description Gets just the filename part (without path or extension) from the filename passed to `Read()`. ### Method `CallGraph::GetFilename` ### Returns `std::string` - Base filename without directory path or file extension. ### Example ```cpp std::string filename = call_graph.GetFilename(); // If Read() was called with "/path/to/binary.bin", returns "binary" ``` ``` -------------------------------- ### Get Database Filename Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-database-writer.md Retrieves the path to the SQLite database file. This is an alternative method to access the file path. ```cpp const std::string& filename() const ``` -------------------------------- ### Download Dependencies for BinDiff Source: https://github.com/google/bindiff/blob/main/README.md Download necessary dependencies like BinExport and IDA SDK before configuring the build. Ensure the paths are correct for your system. ```bash mkdir -p build/out git clone https://github.com/google/binexport build/binexport unzip -q -d build/idasdk ``` -------------------------------- ### FlowGraph::GetVertex Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-flow-graph.md Performs O(logn) binary search to find the vertex (basic block) starting at a specific address. ```APIDOC ## GetVertex(Address address) const ### Description Performs O(logn) binary search to find the vertex (basic block) starting at a specific address. ### Method `GetVertex` ### Parameters #### Path Parameters - **address** (`Address`) - Required - Basic block entry address. ### Response #### Success Response (200) - **Vertex** - Vertex descriptor for the basic block, or an invalid vertex if not found. ### Request Example ```cpp FlowGraph::Vertex bb = flow_graph.GetVertex(0x401050); if (bb != std::numeric_limits::max()) { // Process basic block } ``` ``` -------------------------------- ### ClassifyChanges Function Example Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-change-classifier.md Analyzes a matched function pair (FixedPoint) to detect and record changes using change flags. ```cpp FixedPoint match(&flow_graph1, &flow_graph2, "algorithm_name"); match.SetConfidence(0.95); match.SetSimilarity(0.92); // Analyze what changed ClassifyChanges(&match); // Check results if (match.HasFlag(CHANGE_STRUCTURAL)) { LOG(WARNING) << "Function structure was modified"; } std::string changes = GetChangeDescription(match.GetFlags()); LOG(INFO) << "Changes: " << changes; ``` -------------------------------- ### Populating Instructions from BinExport Proto Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-instruction.md This C++ snippet shows how instructions are populated from BinExport protocol buffers, creating an `Instructions` object from instruction prototypes. ```cpp // From BinExport2 proto: // for (const auto& insn_proto : proto_basic_block.instructions) { // Instructions instructions; // instructions.emplace_back(&cache, // insn_proto.address, // insn_proto.mnemonic, // insn_proto.prime); // } ``` -------------------------------- ### Get Call Graph Comments (Const) Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-call-graph.md Provides read-only access to the collection of comments stored at the call graph level. ```cpp const CommentsByOperatorId& GetComments() const ``` -------------------------------- ### Set YFILES_DIR and Build GUI (Windows) Source: https://github.com/google/bindiff/blob/main/README.md Sets the YFILES_DIR environment variable and builds the shadow JAR for the BinDiff Java GUI on Windows. ```bash set YFILES_DIR= cd java gradle shadowJar ``` -------------------------------- ### Include Header and Namespace Usage Source: https://github.com/google/bindiff/blob/main/_autodocs/README.md Demonstrates the standard C++ include directive for BinDiff headers and how to use the bindiff namespace. ```cpp #include "third_party/zynamics/bindiff/header.h" // Using the bindiff namespace using namespace security::bindiff; // OR security::bindiff::Function(args); ``` -------------------------------- ### Calculate Match Confidence Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-differ.md Calculates the confidence value for a match using its histogram. Use this to get a quality metric for the match. ```cpp Histogram histogram; GetCountsAndHistogram(flow_graphs1, flow_graphs2, fixed_points, &histogram, &counts); Confidences confidences; double confidence = GetConfidence(histogram, &confidences); LOG(INFO) << "Match confidence: " << confidence; ``` -------------------------------- ### Get Instruction Mnemonic Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-instruction.md Retrieves the instruction mnemonic string from the cache. Requires a pointer to the cache used during instruction creation. ```cpp std::string mnemonic = insn.GetMnemonic(&cache); LOG(INFO) << "Instruction: " << mnemonic; ``` -------------------------------- ### Get Instruction Prime Signature Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-instruction.md Retrieves the prime signature of an instruction, which is used for fast matching of similar instruction sequences. ```cpp uint32_t prime = insn.GetPrime(); // Used to calculate basic block prime by multiplying all instruction primes ``` -------------------------------- ### Get Address from Vertex Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-call-graph.md Retrieves the entry point address of a function represented by a given vertex descriptor. This operation has O(1) complexity. ```cpp Address func_address = call_graph.GetAddress(vertex); ``` -------------------------------- ### Set YFILES_DIR and Build GUI (Linux/macOS) Source: https://github.com/google/bindiff/blob/main/README.md Sets the YFILES_DIR environment variable and builds the shadow JAR for the BinDiff Java GUI on Linux or macOS. ```bash export YFILES_DIR= cd java gradle shadowJar ``` -------------------------------- ### Getting Display Name for a Statistic Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-statistics.md Shows how to retrieve a human-readable name for a specific statistic type using the GetDisplayName static method. ```cpp absl::string_view name = Counts::GetDisplayName(Counts::kFunctionMatchesLibrary); LOG(INFO) << "Statistic: " << name; // Output: "Statistic: Function Matches (Library)" ``` -------------------------------- ### Get Hash Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-flow-graph.md Returns the string reference hash for a basic block or entire function. Use the vertex parameter for a specific basic block. ```cpp uint32_t bb_hash = flow_graph.GetHash(vertex); uint32_t func_hash = flow_graph.GetHash(); ``` -------------------------------- ### Algorithm Matching Sequence Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Illustrates how the order of algorithms in the configuration affects the matching process, with earlier algorithms providing more confident matches. ```cpp // Configuration order determines matching sequence MatchingSteps steps; for (const auto& algo_config : config.call_graph_algorithms()) { if (algo_config.enabled()) { // Create and add algorithm in this order steps.push_back(CreateAlgorithm(algo_config)); } } ``` -------------------------------- ### Get Basic Block Entry Address Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-flow-graph.md Retrieves the entry address of a given basic block vertex. This operation has a constant time complexity. ```cpp Address GetAddress(Vertex vertex) const ``` -------------------------------- ### Write and Read BinDiff Comparison Results Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-database-writer.md This snippet demonstrates the complete workflow of writing comparison results to a database using DatabaseWriter and then reading them back using DatabaseReader. Ensure the database file path is correct. ```cpp // 1. Run comparison and write results { // Run Diff algorithm (see differ.h) MatchingContext context(call_graph1, call_graph2, flow_graphs1, flow_graphs2, fixed_points); Diff(&context, call_graph_steps, basic_block_steps); // Write to database auto result = DatabaseWriter::Create("comparison.bd"); if (!result.ok()) { LOG(ERROR) << "Failed to create writer"; return; } auto writer = std::move(result).value(); absl::Status write_status = writer->Write( call_graph1, call_graph2, flow_graphs1, flow_graphs2, fixed_points); if (!write_status.ok()) { LOG(ERROR) << "Failed to write: " << write_status; return; } writer->Close(); } // 2. Later: read results { SqliteDatabase db; db.Open("comparison.bd"); DatabaseReader reader(db, "comparison.bd", "/tmp"); CallGraph cg1, cg2; FlowGraphInfos fgi1, fgi2; FixedPointInfos fps; absl::Status status = reader.Read(cg1, cg2, fgi1, fgi2, fps); if (!status.ok()) { LOG(ERROR) << "Failed to read: " << status; return; } LOG(INFO) << "Found " << fps.size() << " function matches"; LOG(INFO) << "Similarity: " << reader.similarity(); LOG(INFO) << "Confidence: " << reader.confidence(); } ``` -------------------------------- ### Get and Set Executable Filename Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-call-graph.md Manages the filename of the original input binary. Use SetExeFilename to associate the call graph with its source executable. ```cpp const std::string& GetExeFilename() const void SetExeFilename(std::string name) ``` -------------------------------- ### Get Preferred Function Name Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-call-graph.md Retrieves the most readable name for a function, prioritizing the demangled name if available, otherwise using the raw name. ```cpp const std::string& GetGoodName(Vertex vertex) const ``` -------------------------------- ### Use Global BinDiff Configuration Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md This C++ function shows how to access and use the global BinDiff configuration object. It retrieves the configuration using `config::Proto()` and suggests using it for matching algorithms. ```cpp #include "config.h" // Option 1: Use global configuration void UseGlobalConfig() { Config& config = config::Proto(); // Use config for matching algorithms } ``` -------------------------------- ### Get and Set Function Names Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-call-graph.md Retrieves or assigns a user-defined name to a function represented by a vertex. Use this to provide meaningful labels for functions. ```cpp std::string func_name = call_graph.GetName(vertex); call_graph.SetName(vertex, "my_function"); ``` -------------------------------- ### Diff Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-differ.md The main entry point for the BinDiff differ. This function executes the core matching algorithm to establish a partial or complete matching between two binaries. ```APIDOC ## Diff ### Description Main entry point to the differ. Runs the core matching algorithm and produces a partial or complete matching between two binaries. ### Method `void` ### Parameters #### Path Parameters - **context** (`MatchingContext*`) - Yes - Context containing both call graphs, flow graphs, and fixed points to populate - **call_graph_steps** (`const MatchingSteps&`) - Yes - List of matching algorithms for function-level matching - **basic_block_steps** (`const MatchingStepsFlowGraph&`) - Yes - List of matching algorithms for basic block-level matching ### Request Example ```cpp MatchingContext context(call_graph1, call_graph2, flow_graphs1, flow_graphs2, fixed_points); // Set up matching steps (typically loaded from configuration) MatchingSteps call_graph_steps = CreateCallGraphSteps(); MatchingStepsFlowGraph basic_block_steps = CreateBasicBlockSteps(); // Run the diffing algorithm Diff(&context, call_graph_steps, basic_block_steps); // Results are in context.fixed_points_ ``` ``` -------------------------------- ### Set and Get Comments Ported Status Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-fixed-points.md Indicates whether comments have been transferred from the primary to the secondary function. Use this to track comment synchronization. ```cpp void SetCommentsPorted(bool ported) bool GetCommentsPorted() const ``` ```cpp match.SetCommentsPorted(true); if (match.GetCommentsPorted()) { LOG(INFO) << "Comments have been synchronized"; } ``` -------------------------------- ### LoadFromFile(const std::string& filename) Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Loads BinDiff configuration from a specified file, typically 'bindiff.json'. ```APIDOC ## LoadFromFile(const std::string& filename) ### Description Loads configuration from a file (typically bindiff.json). ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **filename** (`const std::string&`) - Required - Path to configuration file ### Returns `absl::StatusOr` - Parsed configuration or error status. ### Request Example ```cpp auto result = config::LoadFromFile("/etc/bindiff/bindiff.json"); if (!result.ok()) { LOG(ERROR) << "Failed to load config: " << result.status(); return; } Config config = std::move(result).value(); ``` ``` -------------------------------- ### Set and Get Similarity Score Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-fixed-points.md Sets or retrieves the similarity score for a match, ranging from 0.0 to 1.0. This indicates how similar the matched items are. ```cpp void SetSimilarity(double similarity) double GetSimilarity() const ``` -------------------------------- ### Defaults() Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Returns the default (hardcoded) BinDiff configuration without loading from the filesystem. ```APIDOC ## Defaults() ### Description Returns the default (hardcoded) configuration without loading from filesystem. ### Returns `const Config&` - Read-only reference to default configuration. ### Example ```cpp const auto& defaults = config::Defaults(); LOG(INFO) << "Default algorithms count: " << defaults.call_graph_algorithms_size(); ``` ``` -------------------------------- ### Set and Get Confidence Score Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-fixed-points.md Sets or retrieves the confidence score for a match, ranging from 0.0 to 1.0. Use this to evaluate the reliability of a match. ```cpp void SetConfidence(double confidence) double GetConfidence() const ``` ```cpp match.SetConfidence(0.95); double conf = match.GetConfidence(); if (conf > 0.8) { LOG(INFO) << "High confidence match"; } ``` -------------------------------- ### Configure Database Writer Options Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-database-writer.md Defines configuration options for creating a DatabaseWriter. Use this to customize behavior like including function names. ```cpp struct DatabaseWriterOptions { DatabaseWriterOptions& set_include_function_names(bool value) { include_function_names = value; return *this; } bool include_function_names = true; } ``` ```cpp DatabaseWriter::Options opts; opts.set_include_function_names(false); // Don't include names for privacy ``` -------------------------------- ### Initialize Database Transmuter Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-database-writer.md Constructs a DatabaseTransmuter to update an existing comparison database with new matches. Requires the database and previous match information. ```cpp DatabaseTransmuter(SqliteDatabase& database, const FixedPointInfos& fixed_point_infos) ``` ```cpp auto writer = DatabaseWriter::Create("results.db").value(); FixedPointInfos existing_matches; // ... populate from database ... DatabaseTransmuter transmuter(writer->database(), existing_matches); ``` -------------------------------- ### Matching and Analysis Source: https://github.com/google/bindiff/blob/main/_autodocs/README.md Details the core algorithms for matching binaries, including function-level and instruction-level matching, and change classification. ```APIDOC ## Matching and Analysis ### Diff() Function #### Description Orchestrates the binary comparison and matching process. This is the primary function for initiating a diff operation. ### Read() Function #### Description Loads BinExport files, which are required as input for the `Diff()` function. ### FixedPoint Class #### Description Represents a function-level match between two binaries. Provides confidence and similarity scoring, and change classification flags. ### BasicBlockFixedPoint Class #### Description Represents a match at the basic block level within a function. ### Instruction Class #### Description Represents an individual instruction in the disassembled code. Supports mnemonic caching and longest common subsequence matching. ### ClassifyChanges() Function #### Description Classifies the differences between matched functions or basic blocks. Can operate on single matches or batches of matches. ### ChangeType Enumeration #### Description Defines the seven distinct types of changes that can be detected between binary components. ``` -------------------------------- ### Configure BinDiff Build without IDA Source: https://github.com/google/bindiff/blob/main/README.md Configure the build to exclude IDA Pro integration. This is useful if IDA Pro is not installed or not required for the build. ```bash cmake -S . -B build/out -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=build/out \ -DBINDIFF_BINEXPORT_DIR=build/binexport \ -DBINEXPORT_ENABLE_IDAPRO=OFF ``` -------------------------------- ### Instruction Constructor Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-instruction.md Creates an instruction entry with its address, mnemonic, and prime signature, referencing a shared cache. ```APIDOC ## Instruction Constructor ### Description Creates an instruction entry. ### Parameters #### Path Parameters - **cache** (`Cache*`) - Required - Pointer to shared instruction cache for mnemonics - **address** (`Address`) - Required - Instruction address in binary - **mnemonic** (`const std::string&`) - Required - Instruction mnemonic (e.g., "mov", "jmp") - **prime** (`uint32_t`) - Required - Prime signature of the instruction ### Request Example ```cpp Instruction::Cache cache; Instruction insn(&cache, 0x401000, "mov", 17); // 17 is prime for "mov" ``` ``` -------------------------------- ### Custom Matching Algorithm Placeholder Source: https://github.com/google/bindiff/blob/main/_autodocs/INDEX.md This snippet indicates where custom matching algorithms would be implemented. Algorithms are typically provided as matching step plugins. ```cpp // Algorithms are typically provided via matching step plugins // See MatchingStep and MatchingStepFlowGraph interfaces ``` -------------------------------- ### Get String Reference Hash Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-flow-graph.md Retrieves the string reference hash for a basic block or the entire function. Use the vertex parameter for a specific basic block. ```cpp uint32_t bb_hash = flow_graph.GetStringReferences(vertex); uint32_t func_hash = flow_graph.GetStringReferences(); ``` -------------------------------- ### Get Loop Count Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-flow-graph.md Returns the number of loops detected in the flow graph. Loops are identified using the Lengauer-Tarjan algorithm's definition of a back edge. ```cpp uint16_t GetLoopCount() const ``` -------------------------------- ### Get Basic Block Count Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-flow-graph.md Retrieves the total number of basic blocks within the flow graph. This is useful for understanding the overall size and complexity of the graph. ```cpp size_t bb_count = flow_graph.GetBasicBlockCount(); ``` -------------------------------- ### Get and Set C++ Demangled Names Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-call-graph.md Manages the C++ demangled names for functions. Set this if the demangled name differs from the mangled name to improve readability. ```cpp const std::string& GetDemangledName(Vertex vertex) const void SetDemangledName(Vertex vertex, std::string name) ``` -------------------------------- ### BinDiff Configuration Filename Constant Source: https://github.com/google/bindiff/blob/main/_autodocs/configuration.md Defines the standard filename for BinDiff configuration files. ```cpp inline constexpr char kConfigName[] = "bindiff.json" ``` -------------------------------- ### Get Base Filename from CallGraph Source: https://github.com/google/bindiff/blob/main/_autodocs/api-reference-call-graph.md Retrieves the base filename (without path or extension) that was previously provided to the Read() method. Useful for identifying the source binary. ```cpp std::string filename = call_graph.GetFilename(); // If Read() was called with "/path/to/binary.bin", returns "binary" ```