Skip to content
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

Support bpf2bpf calls from ELF files #693

Merged
merged 6 commits into from
Sep 27, 2024
Merged

Conversation

dthaler
Copy link
Contributor

@dthaler dthaler commented Sep 27, 2024

PR #608 added support for bpf2bpf calls when instructions were contiguous, including YAML tests for it.
However PR #638 added support for multiple programs per section, and in that support, instructions for different programs (or subprograms) are not contiguous but are in separate program objects.

This PR adds support for bpf2bpf calls across program objects, including ELF tests for it (using an exising ebpf-sample sample). In the existing bpf2bpf.o sample, "func" calls "prog1" in a valid way. "prog1" is not verifiable on its own since its prototype doesn't match the program type, and a negative test is added for this case.

(The type change to the get_value() argument is to resolve a compiler warning.)

Summary by CodeRabbit

  • New Features

    • Enhanced handling of function relocations and subprogram management in ELF file processing.
    • Introduced a new macro for testing programs expected to fail verification.
  • Bug Fixes

    • Improved accuracy in program verification through additional test cases.
  • Documentation

    • Updated method signatures for better clarity and consistency.

Copy link

coderabbitai bot commented Sep 27, 2024

Walkthrough

The changes involve significant modifications to the src/asm_files.cpp file, focusing on function relocation and subprogram management within ELF file processing. Key updates include the introduction of a new structure for queuing relocation requests and the removal of the relocate_function function. Additionally, a new macro, TEST_PROGRAM_REJECT, is added in src/test/test_verify.cpp to enhance testing capabilities for programs expected to fail verification, along with new test cases utilizing this macro.

Changes

Files Change Summary
src/asm_files.cpp Updated function signatures for get_symbol_name_and_section_index and get_value to use const references and changed parameter types. Removed relocate_function and introduced function_relocation structure. Added static functions for subprogram management.
src/test/test_verify.cpp Introduced new macro TEST_PROGRAM_REJECT for testing programs expected to fail verification. Added two test cases, one for a failing program and one for a passing program.

Sequence Diagram(s)

sequenceDiagram
    participant MainProgram
    participant ELFProcessor
    participant FunctionRelocationQueue

    MainProgram->>ELFProcessor: Read ELF file
    ELFProcessor->>FunctionRelocationQueue: Queue relocation requests
    FunctionRelocationQueue->>ELFProcessor: Process queued relocations
    ELFProcessor->>MainProgram: Return processed ELF
Loading

🐇 In the code where functions play,
A rabbit hops and saves the day.
With relocations queued in line,
Testing fails, but that's just fine!
New macros dance, and cases grow,
In this land of code, we flow! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between f005051 and 6238ab6.

📒 Files selected for processing (1)
  • src/asm_files.cpp (7 hunks)
🧰 Additional context used
📓 Learnings (1)
src/asm_files.cpp (1)
Learnt from: dthaler
PR: vbpf/ebpf-verifier#693
File: src/asm_files.cpp:63-63
Timestamp: 2024-09-27T03:48:52.280Z
Learning: When working with the ELFIO library, `ELFIO::Elf_Half` is the correct type for return values of 16-bit fields provided by the library and should not be changed to `ELFIO::Elf_Xword`.
🔇 Additional comments (8)
src/asm_files.cpp (8)

63-63: Consistent Use of ELFIO::Elf_Xword for Symbol Indices

Updating the index parameter type to ELFIO::Elf_Xword enhances support for larger symbol tables and ensures consistency across functions handling symbol indices.

Also applies to: 77-77


202-209: Introduction of function_relocation Structure

The addition of the function_relocation structure effectively encapsulates relocation data for function calls, improving the clarity and organization of the code related to function relocations.


211-231: Robust Implementation of append_subprogram Function

The append_subprogram function is well-implemented to locate and append subprograms by name. The checks for zero-size subprograms and handling of subprogram offsets enhance the reliability of the function.


233-263: Efficient Handling of Function Relocations in append_subprograms

The append_subprograms function effectively processes queued function relocations, ensuring that each subprogram is appended only once and updating the instruction's immediate value correctly. The addition of checks for prog_index bounds prevents potential out-of-bounds access.


257-260: Preventing Integer Overflow in Offset Calculation

Adding the range check for offset_diff ensures that the offset difference fits within the int32_t range before casting. This prevents potential integer overflow issues, enhancing the robustness of the relocation process.


358-358: Initialization of function_relocations Vector

Initializing the function_relocations vector prepares the codebase for collecting function relocation data, facilitating the new relocation handling mechanism.


419-426: Queueing Function Relocations for Deferred Processing

By queuing function relocations using the function_relocation structure, the code defers relocation processing until all programs are loaded. This approach improves the manageability and modularity of the relocation logic.


447-454: Sequentially Appending Subprograms After Program Loading

The loop to append subprograms after all programs have been read ensures that any called subprograms are included in the main program code, facilitating complete verification and execution.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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 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: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between c50905b and 271112f.

📒 Files selected for processing (2)
  • src/asm_files.cpp (7 hunks)
  • src/test/test_verify.cpp (2 hunks)
🔇 Additional comments (7)
src/test/test_verify.cpp (4)

79-82: LGTM: New macro for testing programs expected to fail verification.

The TEST_PROGRAM_REJECT macro is well-defined and consistent with the existing testing framework. It correctly sets up a test case for programs that should fail verification, which enhances the test coverage.


505-505: LGTM: New test case for subprogram expected to fail verification.

This test case correctly uses the new TEST_PROGRAM_REJECT macro to test the "plus1" subprogram, which is expected to fail verification. This adds valuable coverage to the test suite.


506-506: LGTM: New test case for subprogram expected to pass verification.

This test case appropriately uses the TEST_PROGRAM macro to test the "func" program, which is expected to pass verification. The comment clarifies that this subprogram can be called from the main program, explaining its expected behavior.


79-82: Summary: Enhancements to eBPF program verification testing.

The changes in this file improve the test coverage for eBPF program verification:

  1. A new macro TEST_PROGRAM_REJECT has been added to facilitate testing of programs expected to fail verification.
  2. Two new test cases have been added:
    • One using TEST_PROGRAM_REJECT to test a subprogram expected to fail verification.
    • Another using TEST_PROGRAM to test a subprogram expected to pass verification.

These additions enhance the robustness of the test suite by explicitly covering both positive and negative test scenarios for bpf2bpf calls across separate program objects.

Also applies to: 505-506

src/asm_files.cpp (3)

Line range hint 63-76: Consistent Type Usage for Index Parameter

The function get_symbol_name_and_section_index now uses ELFIO::Elf_Xword for the index parameter instead of ELFIO::Elf_Word. This change allows the function to handle larger symbol tables, which is consistent with the ELF64 specification and ensures correctness when processing files with a large number of symbols.


Line range hint 77-90: Update Index Parameter Type to ELFIO::Elf_Xword

The get_value function's index parameter has been updated from ELFIO::Elf_Word to ELFIO::Elf_Xword. This adjustment aligns with the changes made in get_symbol_name_and_section_index and ensures that the function can handle symbol tables with a larger number of entries, enhancing compatibility with ELF64 files.


411-421: Verify Correctness of prog_index Assignment

In the creation of function_relocation, prog_index is set using res.size() before prog is pushed into res:

function_relocation fr{.prog_index = res.size(), /* ... */ };

Since prog is added to res after this point, there is a possibility that prog_index might not correctly reference the current program.

Please confirm that res.size() accurately represents the index of the current prog. If not, consider adjusting the code to add prog to res before this assignment or modify prog_index accordingly.

src/asm_files.cpp Outdated Show resolved Hide resolved
src/asm_files.cpp Outdated Show resolved Hide resolved
src/asm_files.cpp Outdated Show resolved Hide resolved
src/asm_files.cpp Outdated Show resolved Hide resolved
Signed-off-by: Dave Thaler <[email protected]>
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 271112f and 6590861.

📒 Files selected for processing (1)
  • src/asm_files.cpp (7 hunks)
🔇 Additional comments (3)
src/asm_files.cpp (3)

202-207: Declaration of function_relocation struct is appropriate

The new struct function_relocation neatly encapsulates the data required for queuing function relocations, enhancing code clarity and maintainability.


443-450: Logic for appending subprograms is correctly implemented

The append_subprograms function appropriately processes function relocations and appends subprograms to ensure that all calls are resolved within the same program for verification.


Line range hint 63-77: Verify usage of updated function parameter types

The functions get_symbol_name_and_section_index and get_value now have the index parameter type changed from ELFIO::Elf_Word to ELFIO::Elf_Xword. Ensure that all calls to these functions throughout the codebase are updated to use ELFIO::Elf_Xword to prevent potential type mismatches or truncation.

Run the following script to find and review all usages:

src/asm_files.cpp Outdated Show resolved Hide resolved
src/asm_files.cpp Outdated Show resolved Hide resolved
Signed-off-by: Dave Thaler <[email protected]>
Signed-off-by: Dave Thaler <[email protected]>
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 6590861 and b08a7cb.

📒 Files selected for processing (1)
  • src/asm_files.cpp (7 hunks)
🔇 Additional comments (5)
src/asm_files.cpp (5)

209-229: append_subprogram Function Implementation

The append_subprogram function correctly locates and appends the subprogram instructions to the main program. The checks for zero-size subprograms and proper error handling are appropriate.


231-259: Efficient Management of Function Relocations in append_subprograms

The append_subprograms function efficiently handles function relocations and ensures that each subprogram is appended only once. The use of subprogram_offsets to track appended subprograms improves performance by avoiding duplicate processing.


421-428: Confirm Correctness of Function Relocation Handling

The code queues up function relocations for local call instructions. Ensure that the relocation_entry_index corresponds correctly to the target function, and that the function name resolution is accurate.


445-445: Avoid Storing References in Containers

The segment_to_program map stores references to raw_program objects:

std::map<std::string, raw_program&> segment_to_program;

Storing references in standard containers can lead to dangling references if the referenced objects are moved or if the container is copied. Consider storing pointers or indices instead to ensure the references remain valid.


379-384: ⚠️ Potential issue

Remove Unused Variable subprograms

The variable subprograms is declared and program_name is inserted into it, but it is not used elsewhere in the code. This unused variable can be safely removed to clean up the code.

Apply this diff to remove the unused variable:

-                std::set<string> subprograms{};
-                subprograms.insert(program_name);

Likely invalid or redundant comment.

src/asm_files.cpp Show resolved Hide resolved
src/asm_files.cpp Show resolved Hide resolved
@coveralls
Copy link

coveralls commented Sep 27, 2024

Coverage Status

coverage: 90.398% (+0.03%) from 90.365%
when pulling 6238ab6 on dthaler:bpf2bpf-elf
into c50905b on vbpf:main.

Signed-off-by: Dave Thaler <[email protected]>
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: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between b08a7cb and f005051.

📒 Files selected for processing (1)
  • src/asm_files.cpp (7 hunks)
🧰 Additional context used
📓 Learnings (1)
src/asm_files.cpp (1)
Learnt from: dthaler
PR: vbpf/ebpf-verifier#693
File: src/asm_files.cpp:63-63
Timestamp: 2024-09-27T03:48:52.280Z
Learning: When working with the ELFIO library, `ELFIO::Elf_Half` is the correct type for return values of 16-bit fields provided by the library and should not be changed to `ELFIO::Elf_Xword`.
🔇 Additional comments (3)
src/asm_files.cpp (3)

202-209: Well-documented function_relocation structure

The added documentation above the function_relocation struct definition enhances code readability and maintainability.


63-63: Consistency in ELFIO Types for Symbol Indices

The functions get_symbol_name_and_section_index and get_value now use ELFIO::Elf_Xword for the index parameter, supporting larger symbol tables. This change improves compatibility with ELF files containing more symbols.

Also applies to: 77-77


253-258: Check for Potential Integer Overflow in Offset Calculation

The code correctly checks for overflow when calculating offset_diff:

int64_t offset_diff = (int64_t)(target_offset - reloc.source_offset - 1);
if (offset_diff < INT32_MIN || offset_diff > INT32_MAX) {
    throw std::runtime_error("Offset difference out of int32_t range for instruction at source offset " +
                             std::to_string(reloc.source_offset));
}
prog.prog[reloc.source_offset].imm = (int32_t)offset_diff;

This ensures that the cast to int32_t is safe and prevents potential errors.

src/asm_files.cpp Show resolved Hide resolved
src/asm_files.cpp Outdated Show resolved Hide resolved
src/asm_files.cpp Outdated Show resolved Hide resolved
src/asm_files.cpp Outdated Show resolved Hide resolved
Signed-off-by: Dave Thaler <[email protected]>
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.

3 participants