Skip to content

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.

@coderabbitai
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

@coderabbitai
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 +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.

@visz11
Copy link
Collaborator

visz11 commented Jul 29, 2025

/refacto-test

1 similar comment
@visz11
Copy link
Collaborator

visz11 commented Jul 29, 2025

/refacto-test

@refacto-test
Copy link

refacto-test bot commented Jul 29, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

1 similar comment
@refacto-test
Copy link

refacto-test bot commented Jul 29, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@visz11
Copy link
Collaborator

visz11 commented Jul 29, 2025

/refacto-test

@refacto-test
Copy link

refacto-test bot commented Jul 30, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@arvi18
Copy link
Author

arvi18 commented Aug 8, 2025

/refacto-test

@refacto-test
Copy link

refacto-test bot commented Aug 8, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-test
Copy link

refacto-test bot commented Aug 8, 2025

Security Review: FunctionID Script

👍 Well Done
Proper Error Handling

Script validates inputs before processing to prevent errors.

Task Monitoring

Uses monitor for cancellation support during long operations.

📝 Additional Comments
Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (1)
Error Handling Improvement

Database save operation lacks specific error handling. Failed database operations could lead to data loss without proper user notification.

			try {
				fidDb.saveDatabase("Saving", monitor);
				println("Function successfully added to database");
			}
			catch (Exception e) {
				printerr("Failed to save database: " + e.getMessage());
			}

Standards:

  • CWE-755
  • OWASP-A06

Comment on lines +106 to +107
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.

Missing Input Validation

Function name from user input is used without validation. Malicious function names could potentially cause injection vulnerabilities when stored in the database.

Suggested change
function.getName(disableNamespaceStripping), offset, domainFile.getName(),
hasTerminator);
String functionName = function.getName(disableNamespaceStripping);
// Validate function name before database insertion
if (functionName == null || functionName.isEmpty()) {
printerr("Invalid function name");
return;
}
fidDb.createNewFunction(library, hashFunction,
functionName, offset, domainFile.getName(),
Standards
  • CWE-20
  • OWASP-A03

Comment on lines +71 to +72
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.

Resource Leak Risk

Database resource opened without try-with-resources pattern. If an exception occurs between opening and the finally block, resource might not be properly closed.

Suggested change
try {
fidDb = fidFile.getFidDB(true);
try (FidDB db = fidFile.getFidDB(true)) {
fidDb = db;
Standards
  • CWE-772
  • OWASP-A06

@visz11
Copy link
Collaborator

visz11 commented Sep 15, 2025

/refacto-test-arvi

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

Code Review: FunctionID Script

👍 Well Done
Function Validation Logic

Comprehensive function size validation prevents processing of unsuitable functions.

Resource Management

Proper database closure in finally block ensures resources are released.

📌 Files Processed
  • Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java
  • Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java
📝 Additional Comments
Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (2)
Incomplete Error Handling

saveDatabase operation lacks specific error handling. If save fails, the user receives no feedback about what went wrong or how to recover, potentially leading to data loss.

Standards:

  • Business-Rule-Error-Reporting
  • Logic-Verification-Operation-Result
  • Algorithm-Correctness-Exception-Handling
Missing Transaction Management

Database operations lack transaction management. If an error occurs between createNewFunction and saveDatabase, the database may be left in an inconsistent state without rollback capability.

Standards:

  • Business-Rule-Data-Consistency
  • Logic-Verification-Transaction-Management
  • Algorithm-Correctness-Operation-Atomicity

Comment on lines +111 to +113
finally {
fidDb.close();
}
Copy link

Choose a reason for hiding this comment

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

Missing Null Check

fidDb.close() is called without checking if fidDb is null. If an exception occurs before fidDb is initialized (line 72), a NullPointerException will be thrown in the finally block, masking the original exception.

Suggested change
finally {
fidDb.close();
}
finally {
if (fidDb != null) {
fidDb.close();
}
}
Standards
  • Logic-Verification-Null-Safety
  • Algorithm-Correctness-Exception-Handling
  • Business-Rule-Resource-Management

FidFile fidFile =
askChoice("FID database", "Choose FID database", userFid, userFid.get(0));
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.

Unchecked Database Operation

The getFidDB call may fail but lacks error handling. If database access fails, the script will throw an exception without proper user feedback about the specific database issue.

Standards
  • Business-Rule-Validation
  • Logic-Verification-Error-Handling
  • Algorithm-Correctness-Exception-Management

@visz11
Copy link
Collaborator

visz11 commented Sep 15, 2025

/refacto-test-arvi

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

Code Review: FunctionID Script

👍 Well Done
Proper Exception Handling

Script implements try-finally block ensuring database closure even when exceptions occur.

Efficient Function Handling

Properly checks function existence before processing, preventing unnecessary operations.

Resource Management

Consistent resource cleanup with try-finally ensures database connections are properly closed.

📌 Files Processed
  • Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java
  • Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java
📝 Additional Comments
Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (3)
Unrestricted Database Access

The script opens the FID database with write access (true parameter) without any access control verification. Consider implementing permission checks before allowing database modifications to prevent unauthorized database alterations.

Standards:

  • CWE-284
  • OWASP-A01
Error Handling Improvement

While the script uses try-finally for database closure, it doesn't handle specific exceptions that may occur during database operations. Adding specific exception handling would improve error reporting and prevent information leakage through unhandled exceptions.

Standards:

  • CWE-209
  • OWASP-A09
Database Operation Batching

Database operations are performed individually rather than batched. The saveDatabase call immediately follows a single function creation, which is inefficient for bulk operations. Consider batching multiple operations before saving for better performance.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Time-Behavior
  • Optimization-Pattern-Batch-Processing
  • Database-Operation-Optimization

Comment on lines +79 to +82
String libraryFamilyName =
askString("Library Family Name", "Choose Library Family Name");
String libraryVersion = askString("Library Version", "Choose Library Version");
String libraryVariant = askString("Library Variant", "Choose Library Variant");
Copy link

Choose a reason for hiding this comment

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

Missing Input Validation

User input for library metadata is accepted without validation before being used to create database entries. This could allow injection of malicious data into the FID database, potentially enabling database corruption or injection attacks when these values are later used in queries.

Suggested change
String libraryFamilyName =
askString("Library Family Name", "Choose Library Family Name");
String libraryVersion = askString("Library Version", "Choose Library Version");
String libraryVariant = askString("Library Variant", "Choose Library Variant");
String libraryFamilyName = askString("Library Family Name", "Choose Library Family Name");
if (libraryFamilyName == null || libraryFamilyName.trim().isEmpty()) {
printerr("Library Family Name cannot be empty");
return;
}
String libraryVersion = askString("Library Version", "Choose Library Version");
if (libraryVersion == null || libraryVersion.trim().isEmpty()) {
printerr("Library Version cannot be empty");
return;
}
String libraryVariant = askString("Library Variant", "Choose Library Variant");
if (libraryVariant == null || libraryVariant.trim().isEmpty()) {
printerr("Library Variant cannot be empty");
return;
}
Standards
  • CWE-20
  • OWASP-A03
  • NIST-SSDF-PW.1

Comment on lines +112 to +113
fidDb.close();
}
Copy link

Choose a reason for hiding this comment

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

Missing Error Handling

The fidDb.close() call doesn't check if fidDb is null before closing, which could cause a NullPointerException if database initialization fails. This would prevent proper error handling and resource cleanup under failure conditions.

Standards
  • ISO-IEC-25010-Performance-Efficiency-Resource-Utilization
  • Optimization-Pattern-Resource-Management
  • Error-Handling-Robustness

@visz11
Copy link
Collaborator

visz11 commented Sep 15, 2025

/refacto-test-arvi

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

Code Review: FunctionID Script

👍 Well Done
Resource Management

Proper resource cleanup in finally block ensures FidDB is always closed regardless of execution path.

Clear Function Naming

Method names clearly convey purpose and functionality throughout the code.

Error Handling

Consistent error checking with early returns improves maintainability and readability.

📌 Files Processed
  • Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java
  • Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java
📝 Additional Comments
Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java (1)
Method Visibility Change

Changing class visibility from package-private to public without apparent architectural necessity. This increases API surface area and creates potential coupling issues, making future refactoring more difficult.

Standards:

  • Clean-Code-Class-Organization
  • Maintainability-Quality-Encapsulation
  • SOLID-OCP
Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (6)
Error Message Enhancement

Error messages lack detail about recovery actions or next steps. Adding guidance on how to resolve each error condition would improve user experience and reduce troubleshooting time when script execution fails.

Standards:

  • ISO-IEC-25010-Reliability-Maturity
  • ISO-IEC-25010-Functional-Appropriateness
  • SRE-Error-Handling
Missing Transaction Management

The code performs database operations without explicit transaction management. If an error occurs between createNewFunction and saveDatabase, the database could be left in an inconsistent state. Adding transaction boundaries would ensure atomicity.

Standards:

  • Business-Rule-Data-Consistency
  • Logic-Verification-Transaction-Integrity
  • Algorithm-Correctness-State-Management
Input Validation Needed

The function name from the current program is used without validation when creating a new function in the FID database. If function names contain special characters or malicious sequences, they could potentially cause unexpected behavior or data corruption in the database.

Standards:

  • CWE-20
  • OWASP-A03
  • NIST-SSDF-PW.1
Exception Documentation Missing

Method declares it throws generic Exception without documenting specific exception types that callers should handle. This reduces reliability by preventing callers from implementing targeted exception handling strategies for different failure scenarios.

Standards:

  • ISO-IEC-25010-Reliability-Fault-Tolerance
  • ISO-IEC-25010-Functional-Completeness
  • DbC-Interface-Contract
  • SRE-Error-Handling
Improve Error Handling

The script attempts to open the database with write access but doesn't handle potential failure scenarios like permission issues or database corruption. Adding specific exception handling would improve error reporting and user experience.

Standards:

  • Logic-Verification-Error-Handling
  • Business-Rule-User-Experience
  • Algorithm-Correctness-Robustness
Resource Leak Risk

The script properly closes the database in a finally block, but doesn't handle exceptions that might occur during fidDb.close() itself. If close() throws an exception, it could lead to resource leakage. Consider adding nested try-catch for the close operation.

Standards:

  • CWE-772
  • OWASP-A06
  • NIST-SSDF-PW.1

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

No review comments were generated during this review iteration of the PR.

@visz11
Copy link
Collaborator

visz11 commented Sep 15, 2025

/refacto-test-arvi

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

Code Review: FunctionID Component

👍 Well Done
Proper Resource Management

Using try-finally ensures database is properly closed even when exceptions occur.

Function Terminator Detection

Properly exposed findTerminator method enables reuse in the new script.

Library Creation Logic

Comprehensive library creation workflow handles both new and existing library scenarios.

📌 Files Processed
  • Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java
  • Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java
📝 Additional Comments
Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (3)
Database Access Optimization

Database is opened with write access (true parameter) and later saved. Consider optimizing database operations by batching changes or using transactions to minimize I/O operations, especially if this script might be extended to handle multiple functions.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Resource-Utilization
  • Database-Access-Optimization
  • Transaction-Management-Pattern
Library Selection Logic

The logic checks for null libraries list but fidDb.getAllLibraries() is unlikely to return null based on method naming convention. This creates unnecessary null check logic that complicates the control flow without providing value.

Standards:

  • Logic-Verification-Control-Flow
  • Algorithm-Correctness-Defensive-Programming
Function Hash Reuse

The hashFunction calculation is computationally intensive and should be reused where possible. The current implementation properly calculates it once and reuses it, maintaining good performance. Consider documenting this optimization pattern for future maintainers.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Time-Behavior
  • Optimization-Pattern-Computation-Reuse
  • Code-Documentation-Best-Practice

import ghidra.util.task.TaskMonitor;

class FidServiceLibraryIngest {
public class FidServiceLibraryIngest {
Copy link

Choose a reason for hiding this comment

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

Visibility Modifier Change

Changing class visibility from package-private to public without apparent need exposes implementation details. This increases API surface area and reduces encapsulation, making future refactoring more difficult as external code may depend on this class.

Standards
  • SOLID-OCP
  • Maintainability-Quality-Encapsulation
  • Clean-Code-Class-Organization

* @throws CancelledException if the user cancels
*/
private static boolean findTerminator(Function function, TaskMonitor monitor)
public static boolean findTerminator(Function function, TaskMonitor monitor)
Copy link

Choose a reason for hiding this comment

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

Method Visibility Change

Method visibility changed from private to public without clear architectural justification. This exposes implementation details and creates potential coupling points. Consider if a more targeted interface approach would better preserve encapsulation.

Standards
  • SOLID-OCP
  • Maintainability-Quality-Encapsulation
  • Clean-Code-Method-Access

@visz11
Copy link
Collaborator

visz11 commented Sep 15, 2025

/refacto-test-arvi

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

@refacto-visz
Copy link

refacto-visz bot commented Sep 15, 2025

Code Review: FunctionID Script Enhancements

👍 Well Done
Proper Exception Handling

Consistent use of try-finally block ensures database resources are properly closed.

Clear Error Handling

The script includes proper error checking with descriptive messages before proceeding with operations.

User Interface Flow

Good interactive flow with appropriate user prompts for selecting databases and libraries.

📌 Files Processed
  • Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java
  • Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java
📝 Additional Comments
Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidServiceLibraryIngest.java (2)
Public Method Exposure

The FidServiceLibraryIngest class and findTerminator method were changed from private/package-private to public, potentially expanding the attack surface. Consider whether this exposure is necessary or if more restricted access would provide better encapsulation and security.

Standards:

  • CWE-749
  • OWASP-A04
  • NIST-SSDF-PW.7
Visibility Modifier Change

The class and method visibility were changed from package-private to public. This exposes implementation details that may not be intended for external use, potentially creating unintended dependencies and making future refactoring more difficult.

Standards:

  • Clean-Code-Class-Organization
  • Maintainability-Quality-Encapsulation
  • Design-Pattern-Information-Hiding
Ghidra/Features/FunctionID/ghidra_scripts/AddSingleFunction.java (1)
Error Message Consistency

Error messages use inconsistent formatting with one message containing a question mark. Standardizing error message format improves maintainability by making the code more predictable and easier to understand.

Standards:

  • Clean-Code-Comments
  • Maintainability-Quality-Consistency

DomainFile domainFile = getCurrentProgram().getDomainFile();

fidDb.createNewFunction(library, hashFunction,
function.getName(disableNamespaceStripping), offset, domainFile.getName(),
Copy link

Choose a reason for hiding this comment

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

User Input Validation

Function names from user input are stored in the FID database without validation. Malicious function names could potentially be used for injection attacks when the database is later queried or data is displayed, potentially leading to XSS or SQL injection depending on how the database is implemented.

Standards
  • CWE-20
  • OWASP-A03
  • NIST-SSDF-PW.1

Comment on lines +38 to +39
@Override
protected void run() throws Exception {
Copy link

Choose a reason for hiding this comment

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

Excessive Method Responsibility

The run() method handles multiple responsibilities: validation, user interaction, database operations, and function creation. This violates Single Responsibility Principle and makes maintenance more difficult as changes to one aspect affect the entire method.

Standards
  • SOLID-SRP
  • Clean-Code-Functions
  • Refactoring-Extract-Method

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