Skip to content

FunctionID: Add AddSingleFunction.java Ghidra script #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

arvi18
Copy link

@arvi18 arvi18 commented Apr 21, 2025

Fixes NationalSecurityAgency#5212

Introduction

As described in the linked issue there is currently no way to add a single function to a FID DB which is something I have wanted for a long time as well. The Ghidra script AddSingleFunction.java now implements this functionality.

Overview of the script

Prerequisites:

  • A FID DB must be created and attached.
  • An address must be selected in the listing view.

The script checks if there is any available library in the FID DB. If a library exists the user can select it. If not the user will be prompted to create one. The user can then decide whether to preserve the namespaces of the selected function or save only the basename. Finally the function entry is saved.

Testing

Empty FID DB (create new library)

Select a function (rayon::main):

image

Run AddSingleFunction.java:

image

image

image

image

image

List the FID DB content with ListFunctions.java:

$ cat fid-list.txt
rust-rayon rust_rayon::main

Non-empty FID DB (already contains at least one library)

Select a function (crossbeam_deque::deque::Stealer<T>::steal):

image

Run AddSingleFunction.java:

image

image

image

List the FID DB content with ListFunctions.java:

$ cat fid-list.txt
rust-rayon crossbeam_deque::deque::Stealer<T>::steal
rust-rayon rust_rayon::main

Additional notes

I had to make FidServiceLibraryIngest and findTerminator() public because they are required to calculate hasTerminator which is passed to createNewFunction(). If this is not allowed let me know and I will duplicate findTerminator() instead.

Summary by CodeRabbit

  • New Features

    • Added a script enabling users to add the current function to a selected Function ID (FID) database library with guided prompts for library and function details.
  • Improvements

    • Increased accessibility of function analysis tools to support wider usage within the application.

Copy link

coderabbitai bot commented Apr 21, 2025

Walkthrough

A new Ghidra script, AddSingleFunction.java, was introduced to allow users to add the function at the current address to a selected Function ID (FID) database library. The script guides the user through selecting or creating a library, configuring options, and then records the function's hash and metadata into the chosen library. Additionally, the visibility of the FidServiceLibraryIngest class and its findTerminator method was changed to public, making them accessible to external code, including the new script.

Changes

File(s) Change Summary
Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java Added a new Ghidra script to add the current function to a user-selected FID database library.
Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java Changed class and method visibility to public for FidServiceLibraryIngest and its findTerminator method.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AddSingleFunction Script
    participant FidService
    participant FID Database

    User->>AddSingleFunction Script: Run script
    AddSingleFunction Script->>AddSingleFunction Script: Validate program, address, function
    AddSingleFunction Script->>FidService: Compute function hash
    AddSingleFunction Script->>User: Prompt to select FID database
    User->>AddSingleFunction Script: Select FID database
    AddSingleFunction Script->>FID Database: Open database
    AddSingleFunction Script->>FID Database: Fetch libraries
    alt No libraries exist
        AddSingleFunction Script->>User: Prompt for new library details
        User->>AddSingleFunction Script: Provide details
        AddSingleFunction Script->>FID Database: Create new library
    else Libraries exist
        AddSingleFunction Script->>User: Select existing library
        User->>AddSingleFunction Script: Select library
    end
    AddSingleFunction Script->>User: Prompt for namespace stripping
    User->>AddSingleFunction Script: Respond
    AddSingleFunction Script->>FidServiceLibraryIngest: Check for terminator
    AddSingleFunction Script->>FID Database: Add function record
    AddSingleFunction Script->>FID Database: Save and close
Loading

Poem

In Ghidra’s warren, scripts now bloom,
A single function finds its room.
With hashes made and choices clear,
New libraries or old appear.
Public doors now open wide,
For terminators none can hide!
🐇✨


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (1)

34-115: Consider adding more documentation comments to improve maintainability.

While the script is well-structured, adding more documentation comments explaining the purpose and logic of different sections would improve maintainability and help future developers understand the code more easily.

 public class AddSingleFunction extends GhidraScript {
 
+	/**
+	 * FID database instance that will be used to store the function
+	 */
 	private FidDB fidDb = null;
 
 	@Override
 	protected void run() throws Exception {
+		// Validate prerequisites: program, address and function
 
 		if (currentProgram == null) {
 			printerr("No current program");
 			return;
 		}
 		// ... existing code ...
 
+		// Calculate function hash
 		FidService service = new FidService();
 		FidHashQuad hashFunction = service.hashFunction(function);
 		// ... existing code ...
 
+		// Retrieve and select FID database
 		FidFileManager fidFileManager = FidFileManager.getInstance();
 		// ... existing code ...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2abfd4e and d765288.

📒 Files selected for processing (2)
  • Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (1 hunks)
  • Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java (2 hunks)
🔇 Additional comments (11)
Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java (2)

40-40: LGTM: Class visibility changed to public to support external access.

The change from package-private to public visibility allows the new AddSingleFunction script to access this class.


526-527: LGTM: Method visibility changed to public to enable terminator detection.

Making the findTerminator method public and static enables the new script to check if a function contains a terminator instruction, which is necessary for the FID database entry creation process.

Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (9)

17-19: LGTM: Clear and concise script description.

The script description correctly states its purpose and is properly categorized under FunctionID.


41-54: LGTM: Proper validation of prerequisites.

The script correctly validates that the current program, address, and function exist before proceeding, providing appropriate error messages when conditions aren't met.


56-61: LGTM: Function hash verification.

The script properly verifies that the function can be hashed and terminates with an appropriate message if the function is too small.


63-70: LGTM: FID database availability check and selection.

The script validates that FID databases are available and provides a user selection prompt.


71-94: LGTM: Library handling logic.

The script correctly handles both cases: creating a new library when none exist or selecting an existing one from the FID database.


95-98: LGTM: Optional namespace stripping configuration.

Providing the option to disable namespace stripping gives users flexibility in how function names are stored in the FID database.


101-101: LGTM: Usage of the now-public findTerminator method.

The script correctly uses the newly exposed FidServiceLibraryIngest.findTerminator method to determine if the function has a terminator.


105-107: LGTM: Function registration with appropriate attributes.

The script creates a new function entry in the FID database with all required attributes: library, hash, name (with namespace handling option), offset, source file name, and terminator status.


109-113: LGTM: Proper resource management.

The script properly saves changes to the database and ensures it's closed in a finally block, following good resource management practices.

@visz11
Copy link
Collaborator

visz11 commented Apr 23, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 23, 2025

✅ Actions performed

Full review triggered.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (2)

63-70: Consider improving error message for no available FID databases.

The error message "No available FID DB" is clear but doesn't provide guidance on how to resolve the issue.

Consider enhancing the error message to guide users on how to add a FID database:

-			printerr("No available FID DB");
+			printerr("No available FID databases. Please add a FID database to your project first.");

34-38: Add success message.

The script currently doesn't inform the user when a function is successfully added to the database.

Consider adding a success message after the function is added:

 			fidDb.createNewFunction(library, hashFunction,
 				function.getName(disableNamespaceStripping), offset, domainFile.getName(),
 				hasTerminator);
+
+			println("Successfully added function " + function.getName(disableNamespaceStripping) + 
+				" to library " + library.getName());
 
 			fidDb.saveDatabase("Saving", monitor);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 2abfd4e and d765288.

📒 Files selected for processing (2)
  • Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (1 hunks)
  • Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java (2 hunks)
🔇 Additional comments (9)
Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java (2)

40-40: Changed class visibility to support new script.

The FidServiceLibraryIngest class visibility has been changed from package-private to public, making it accessible for use in the new AddSingleFunction.java script. This approach allows the script to leverage existing functionality while maintaining separation of concerns.


526-526: Changed method visibility to support functionality in new script.

The findTerminator method visibility has been changed from private to public static, allowing it to be used by the new AddSingleFunction.java script to determine if a function contains a terminator instruction. This is necessary for the function creation process within the script.

Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (7)

17-19: Good script documentation.

The script is well-documented with a concise description and appropriate category annotation, making it easy for users to understand its purpose and find it in Ghidra's script manager.


41-54: Proper prerequisite validation.

The script appropriately checks for the existence of a current program, address, and function before proceeding. This prevents potential null pointer exceptions and provides clear error messages to the user.


56-61: Appropriate early termination for unsuitable functions.

The script correctly checks if the function is too small to be hashed and provides a clear error message in this case. This prevents adding problematic functions to the FID database that wouldn't be useful for matching.


76-89: Good user prompting for library creation.

The script effectively guides users through creating a new library when none exists, collecting all necessary metadata and using current program information where appropriate.


95-98: Clear namespace configuration.

The script provides a clear prompt for configuring namespace stripping, which is an important option when adding functions to a FID database as it affects function name matching.


101-101: Effective use of public API.

The script makes good use of the newly public FidServiceLibraryIngest.findTerminator method to determine if the function contains a terminator instruction, which is necessary for creating accurate function records.


109-113: Proper resource management.

The script correctly uses a try-finally block to ensure the database is closed even if an exception occurs during processing. This prevents resource leaks and database corruption.

Comment on lines +105 to +107
fidDb.createNewFunction(library, hashFunction,
function.getName(disableNamespaceStripping), offset, domainFile.getName(),
hasTerminator);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Missing duplicate check before adding function.

The script adds the function to the database without checking if it already exists, which could lead to duplicate entries.

Consider adding a check to determine if the function already exists in the database:

+			// Check if function already exists in the database
+			List<FunctionRecord> existingFunctions = 
+				fidDb.findFunctionsByLibraryAndName(library, function.getName(disableNamespaceStripping));
+			boolean functionExists = false;
+			for (FunctionRecord existingFunction : existingFunctions) {
+				if (existingFunction.getFullHash() == hashFunction.getFullHash() &&
+					existingFunction.getSpecificHash() == hashFunction.getSpecificHash()) {
+					functionExists = true;
+					break;
+				}
+			}
+			
+			if (functionExists) {
+				println("Function already exists in the database. Skipping.");
+				return;
+			}
+			
 			fidDb.createNewFunction(library, hashFunction,
 				function.getName(disableNamespaceStripping), offset, domainFile.getName(),
 				hasTerminator);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fidDb.createNewFunction(library, hashFunction,
function.getName(disableNamespaceStripping), offset, domainFile.getName(),
hasTerminator);
// Check if function already exists in the database
List<FunctionRecord> existingFunctions =
fidDb.findFunctionsByLibraryAndName(library, function.getName(disableNamespaceStripping));
boolean functionExists = false;
for (FunctionRecord existingFunction : existingFunctions) {
if (existingFunction.getFullHash() == hashFunction.getFullHash() &&
existingFunction.getSpecificHash() == hashFunction.getSpecificHash()) {
functionExists = true;
break;
}
}
if (functionExists) {
println("Function already exists in the database. Skipping.");
return;
}
fidDb.createNewFunction(library, hashFunction,
function.getName(disableNamespaceStripping), offset, domainFile.getName(),
hasTerminator);

Comment on lines +71 to +73
try {
fidDb = fidFile.getFidDB(true);

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Missing exception handling.

The code opens the FID database but doesn't handle specific exceptions that might occur during this operation, such as file not found, permission issues, or database corruption.

Consider adding specific exception handling:

 		try {
 			fidDb = fidFile.getFidDB(true);
+		} catch (IOException e) {
+			printerr("Failed to open FID database: " + e.getMessage());
+			return;
 

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add individual functions to a pre-existing FunctionID database files
3 participants