LCOV - code coverage report
Current view: top level - ballet/sbpf - fd_sbpf_loader.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 813 1008 80.7 %
Date: 2026-03-19 18:19:27 Functions: 23 25 92.0 %

          Line data    Source code
       1             : #include "fd_sbpf_loader.h"
       2             : #include "fd_sbpf_instr.h"
       3             : #include "fd_sbpf_opcodes.h"
       4             : #include "../../util/bits/fd_sat.h"
       5             : #include "../murmur3/fd_murmur3.h"
       6             : 
       7             : #include <assert.h>
       8             : #include <stdio.h>
       9             : 
      10             : /* ELF loader, part 1 **************************************************
      11             : 
      12             :    Start with a static piece of scratch memory and do basic validation
      13             :    of the file content.  Walk the section table once and remember
      14             :    sections of interest.
      15             : 
      16             :    ### Terminology
      17             : 
      18             :    This source follows common ELF naming practices.
      19             : 
      20             :      section:  a named data region present in the ELF file
      21             :      segment:  a contiguous memory region containing sections
      22             :                (not necessarily contiguous in the ELF file)
      23             : 
      24             :      physical address (paddr): Byte offset into ELF file (uchar * bin)
      25             :      virtual  address (vaddr): VM memory address */
      26             : 
      27             : /* Provide convenient access to file header and ELF content */
      28             : 
      29             : __extension__ union fd_sbpf_elf {
      30             :   fd_elf64_ehdr ehdr;
      31             :   uchar         bin[0];
      32             : };
      33             : typedef union fd_sbpf_elf fd_sbpf_elf_t;
      34             : 
      35             : /* FD_SBPF_MM_{...}_ADDR are hardcoded virtual addresses of segments
      36             :    in the sBPF virtual machine.
      37             : 
      38             :    FIXME: These should be defined elsewhere */
      39             : 
      40           0 : #define FD_SBPF_MM_BYTECODE_ADDR (0x0UL)         /* bytecode */
      41       69979 : #define FD_SBPF_MM_RODATA_ADDR   (0x100000000UL) /* readonly program data */
      42     5635606 : #define FD_SBPF_MM_PROGRAM_ADDR  (0x100000000UL) /* readonly program data */
      43           0 : #define FD_SBPF_MM_STACK_ADDR    (0x200000000UL) /* stack */
      44           0 : #define FD_SBPF_MM_HEAP_ADDR     (0x300000000UL) /* heap */
      45           0 : #define FD_SBPF_MM_REGION_SZ     (0x100000000UL) /* max region size */
      46             : 
      47           0 : #define FD_SBPF_PF_X  (1U) /* executable */
      48           0 : #define FD_SBPF_PF_W  (2U) /* writable */
      49           0 : #define FD_SBPF_PF_R  (4U) /* readable */
      50           0 : #define FD_SBPF_PF_RW (FD_SBPF_PF_R|FD_SBPF_PF_W)
      51             : 
      52           0 : #define EXPECTED_PHDR_CNT (4U)
      53             : 
      54             : struct fd_sbpf_range {
      55             :   ulong lo;
      56             :   ulong hi;
      57             : };
      58             : typedef struct fd_sbpf_range fd_sbpf_range_t;
      59             : 
      60             : /* fd_sbpf_range_contains returns 1 if x is in the range
      61             :    [range.lo, range.hi) and 0 otherwise. */
      62             : static inline int
      63     3218825 : fd_sbpf_range_contains( fd_sbpf_range_t const * range, ulong x ) {
      64     3218825 :   return !!(( range->lo<=x ) & ( x<range->hi ));
      65     3218825 : }
      66             : 
      67             : /* Mimics Elf64Shdr::file_range(). Returns a pointer to range (Some) if
      68             :    the section header type is not SHT_NOBITS, and sets range.{lo, hi} to
      69             :    the section header offset and offset + size, respectively. Returns
      70             :    NULL (None) otherwise, and sets both range.{lo, hi} to 0 (the default
      71             :    values for a Rust Range type).
      72             : 
      73             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L87-L93 */
      74             : 
      75             : static fd_sbpf_range_t *
      76             : fd_shdr_get_file_range( fd_elf64_shdr const * shdr,
      77     3260685 :                         fd_sbpf_range_t *     range ) {
      78     3260685 :   if( shdr->sh_type==FD_ELF_SHT_NOBITS ) {
      79          52 :     *range = (fd_sbpf_range_t) { .lo = 0UL, .hi = 0UL };
      80          52 :     return NULL;
      81     3260633 :   } else {
      82     3260633 :     *range = (fd_sbpf_range_t) { .lo = shdr->sh_offset, .hi = fd_ulong_sat_add( shdr->sh_offset, shdr->sh_size ) };
      83     3260633 :     return range;
      84     3260633 :   }
      85     3260685 : }
      86             : 
      87             : /* Converts an ElfParserError code to an ElfError code.
      88             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L112-L132 */
      89             : static int
      90        2363 : fd_sbpf_elf_parser_err_to_elf_err( int err ) {
      91        2363 :   switch( err ) {
      92           0 :     case FD_SBPF_ELF_SUCCESS:
      93           0 :       return err;
      94         129 :     case FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS:
      95         129 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
      96           1 :     case FD_SBPF_ELF_PARSER_ERR_INVALID_PROGRAM_HEADER:
      97           1 :       return FD_SBPF_ELF_ERR_INVALID_PROGRAM_HEADER;
      98        2233 :     default:
      99        2233 :       return FD_SBPF_ELF_ERR_FAILED_TO_PARSE;
     100        2363 :   }
     101        2363 : }
     102             : 
     103             : /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L11-L13 */
     104      193663 : #define FD_SBPF_SECTION_NAME_SZ_MAX (16UL)
     105             : #define FD_SBPF_SYMBOL_NAME_SZ_MAX  (64UL)
     106             : 
     107             : /* ELF loader, part 2 **************************************************
     108             : 
     109             :    Prepare a copy of a subrange of the ELF content: The rodata segment.
     110             :    Mangle the copy by applying dynamic relocations.  Then, zero out
     111             :    parts of the segment that are not interesting to the loader.
     112             : 
     113             :    ### Terminology
     114             : 
     115             :    Shorthands for relocation handling:
     116             : 
     117             :      S: Symbol value (typically an ELF physical address)
     118             :      A: Implicit addend, i.e. the original value of the field that the
     119             :         relocation handler is about to write to
     120             :      V: Virtual address, i.e. the target value that the relocation
     121             :         handler is about to write into where the implicit addend was
     122             :         previously stored */
     123             : 
     124             : ulong
     125         784 : fd_sbpf_program_align( void ) {
     126         784 :   return alignof( fd_sbpf_program_t );
     127         784 : }
     128             : 
     129             : ulong
     130         784 : fd_sbpf_program_footprint( fd_sbpf_elf_info_t const * info ) {
     131         784 :   FD_COMPILER_UNPREDICTABLE( info ); /* Make this appear as FD_FN_PURE (e.g. footprint might depened on info contents in future) */
     132         784 :   if( FD_UNLIKELY( fd_sbpf_enable_stricter_elf_headers_enabled( info->sbpf_version ) ) ) {
     133             :     /* SBPF v3+ no longer needs calldests bitmap */
     134           0 :     return FD_LAYOUT_FINI( FD_LAYOUT_APPEND( FD_LAYOUT_INIT,
     135           0 :       alignof(fd_sbpf_program_t), sizeof(fd_sbpf_program_t) ),
     136           0 :       alignof(fd_sbpf_program_t) );
     137           0 :   }
     138         784 :   return FD_LAYOUT_FINI( FD_LAYOUT_APPEND( FD_LAYOUT_APPEND( FD_LAYOUT_INIT,
     139         784 :     alignof(fd_sbpf_program_t), sizeof(fd_sbpf_program_t) ),
     140         784 :     fd_sbpf_calldests_align(), fd_sbpf_calldests_footprint( info->calldests_max ) ),  /* calldests bitmap */
     141         784 :     alignof(fd_sbpf_program_t) );
     142         784 : }
     143             : 
     144             : fd_sbpf_program_t *
     145             : fd_sbpf_program_new( void *                     prog_mem,
     146             :                      fd_sbpf_elf_info_t const * elf_info,
     147         785 :                      void *                     rodata ) {
     148             : 
     149         785 :   if( FD_UNLIKELY( !prog_mem ) ) {
     150           0 :     FD_LOG_WARNING(( "NULL prog_mem" ));
     151           0 :     return NULL;
     152           0 :   }
     153             : 
     154         785 :   if( FD_UNLIKELY( !elf_info ) ) {
     155           0 :     FD_LOG_WARNING(( "NULL elf_info" ));
     156           0 :     return NULL;
     157           0 :   }
     158             : 
     159         785 :   if( FD_UNLIKELY( ((elf_info->bin_sz)>0U) & (!rodata)) ) {
     160           0 :     FD_LOG_WARNING(( "NULL rodata" ));
     161           0 :     return NULL;
     162           0 :   }
     163             : 
     164             :   /* https://github.com/solana-labs/rbpf/blob/v0.8.0/src/elf_parser/mod.rs#L99 */
     165         785 :   if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong) rodata, FD_SBPF_PROG_RODATA_ALIGN ) ) ){
     166           0 :     FD_LOG_WARNING(( "rodata is not 8-byte aligned" ));
     167           0 :     return NULL;
     168           0 :   }
     169             : 
     170             :   /* Initialize program struct */
     171             : 
     172         785 :   FD_SCRATCH_ALLOC_INIT( laddr, prog_mem );
     173         785 :   fd_sbpf_program_t * prog = FD_SCRATCH_ALLOC_APPEND( laddr, alignof(fd_sbpf_program_t), sizeof(fd_sbpf_program_t) );
     174             : 
     175             :   /* Note that entry_pc and rodata_sz get set during the loading phase. */
     176           0 :   *prog = (fd_sbpf_program_t) {
     177         785 :     .info      = *elf_info,
     178         785 :     .rodata    = rodata,
     179         785 :     .rodata_sz = 0UL,
     180         785 :     .text      = (ulong *)((ulong)rodata + elf_info->text_off), /* FIXME: WHAT IF MISALIGNED */
     181         785 :     .entry_pc  = ULONG_MAX,
     182         785 :   };
     183             : 
     184             :   /* If the text section is empty, then we do not need a calldests map. */
     185         785 :   ulong pc_max = elf_info->calldests_max;
     186         785 :   if( FD_UNLIKELY( fd_sbpf_enable_stricter_elf_headers_enabled( elf_info->sbpf_version ) || pc_max==0UL ) ) {
     187             :     /* No calldests map in SBPF v3+ or if text_cnt is 0. */
     188           1 :     prog->calldests_shmem = NULL;
     189           1 :     prog->calldests       = NULL;
     190         784 :   } else {
     191             :     /* Initialize calldests map. */
     192         784 :     prog->calldests_shmem = fd_sbpf_calldests_new(
     193         784 :           FD_SCRATCH_ALLOC_APPEND( laddr, fd_sbpf_calldests_align(),
     194         784 :                                           fd_sbpf_calldests_footprint( pc_max ) ),
     195           0 :           pc_max );
     196           0 :     prog->calldests = fd_sbpf_calldests_join( prog->calldests_shmem );
     197         784 :   }
     198             : 
     199         785 :   return prog;
     200         785 : }
     201             : 
     202             : void *
     203           0 : fd_sbpf_program_delete( fd_sbpf_program_t * mem ) {
     204             : 
     205           0 :   if( FD_LIKELY( mem->calldests ) ) {
     206           0 :     fd_sbpf_calldests_delete( fd_sbpf_calldests_leave( mem->calldests ) );
     207           0 :   }
     208           0 :   fd_memset( mem, 0, sizeof(fd_sbpf_program_t) );
     209             : 
     210           0 :   return (void *)mem;
     211           0 : }
     212             : 
     213             : /* fd_sbpf_loader_t contains various temporary state during loading. */
     214             : 
     215             : struct fd_sbpf_loader {
     216             :   /* External objects */
     217             :   ulong *              calldests; /* owned by program. NULL if calldests_max = 0 or SBPF v3+ */
     218             :   fd_sbpf_syscalls_t * syscalls;  /* owned by caller */
     219             : };
     220             : typedef struct fd_sbpf_loader fd_sbpf_loader_t;
     221             : 
     222             : /* fd_sbpf_slice_cstr_eq is a helper method for checking equality
     223             :    between a slice of memory to a null-terminated C-string.  Unlike
     224             :    strcmp, this function does not include the null-terminator in the
     225             :    comparison.  Returns 1 if the first slice_len bytes of the slice and
     226             :    cstr are equal, and 0 otherwise. */
     227             : static inline int
     228             : fd_sbpf_slice_cstr_eq( uchar const * slice,
     229             :                        ulong         slice_len,
     230     3843303 :                        char const *  cstr ) {
     231     3843303 :   return !!(slice_len==strlen( cstr ) && fd_memeq( slice, cstr, slice_len ));
     232     3843303 : }
     233             : 
     234             : /* fd_sbpf_slice_cstr_start_with is a helper method for checking that a
     235             :    null-terminated C-string is a prefix of a slice of memory.  Returns 1
     236             :    if the first strlen(cstr) bytes of cstr is a prefix of slice, and 0
     237             :    otherwise. */
     238             : static inline int
     239             : fd_sbpf_slice_cstr_start_with( uchar const * slice,
     240             :                                ulong         slice_len,
     241      124144 :                                char const *  cstr ) {
     242      124144 :   ulong cstr_len = strlen( cstr );
     243      124144 :   return !!(slice_len>=cstr_len && fd_memeq( slice, cstr, cstr_len ));
     244      124144 : }
     245             : 
     246             : /* fd_sbpf_lenient_get_string_in_section queries a single string from a
     247             :    section which is marked as SHT_STRTAB.  Returns an ElfParserError on
     248             :    failure, and leaves *out_slice and *out_slice_len in an undefined
     249             :    state.  On success, returns 0 and sets *out_slice to a pointer into
     250             :    elf_bytes corresponding to the beginning of the string within the
     251             :    section.  *out_slice_len is set to the length of the resulting slice.
     252             :    Note that *out_slice_len does not include the null-terminator of the
     253             :    resulting string.
     254             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L467-L496 */
     255             : int
     256             : fd_sbpf_lenient_get_string_in_section( uchar const *         elf_bytes,
     257             :                                        ulong                 elf_bytes_len,
     258             :                                        fd_elf64_shdr const * section_header,
     259             :                                        uint                  offset_in_section,
     260             :                                        ulong                 maximum_length,
     261             :                                        uchar const **        out_slice,
     262      872209 :                                        ulong *               out_slice_len ) {
     263             :   /* This could be checked only once outside the loop, but to keep the code the same...
     264             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L474-L476 */
     265      872209 :   if( FD_UNLIKELY( section_header->sh_type!=FD_ELF_SHT_STRTAB ) ) {
     266           0 :     return FD_SBPF_ELF_PARSER_ERR_INVALID_SECTION_HEADER;
     267           0 :   }
     268             : 
     269             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L477-L482 */
     270      872209 :   ulong offset_in_file;
     271      872209 :   if( FD_UNLIKELY( __builtin_uaddl_overflow( section_header->sh_offset, offset_in_section, &offset_in_file ) ) ) {
     272           0 :     return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     273           0 :   }
     274             : 
     275      872209 :   ulong string_range_start = offset_in_file;
     276      872209 :   ulong string_range_end   = fd_ulong_min( section_header->sh_offset+section_header->sh_size, offset_in_file+maximum_length );
     277      872209 :   if( FD_UNLIKELY( string_range_end>elf_bytes_len ) ) {
     278           0 :     return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     279           0 :   }
     280             :   /* In rust vec.get([n..n]) returns [], so this is accepted.
     281             :      vec.get([n..m]) with m<n returns None, so it throws ElfParserError::OutOfBounds. */
     282      872209 :   if( FD_UNLIKELY( string_range_end<string_range_start ) ) {
     283           8 :     return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     284           8 :   }
     285             : 
     286             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L486-L495 */
     287      872201 :   uchar * null_terminator_ptr = memchr( (uchar const *)elf_bytes+string_range_start, 0, string_range_end-string_range_start );
     288      872201 :   if( FD_UNLIKELY( null_terminator_ptr==NULL ) ) {
     289           6 :     return FD_SBPF_ELF_PARSER_ERR_STRING_TOO_LONG;
     290           6 :   }
     291             : 
     292      872195 :   *out_slice     = elf_bytes+string_range_start;
     293      872195 :   *out_slice_len = (ulong)(null_terminator_ptr-*out_slice);
     294             : 
     295      872195 :   return FD_SBPF_ELF_SUCCESS;
     296      872201 : }
     297             : 
     298             : /* Registers a target PC into the calldests function registry. Returns
     299             :    0 on success, inserts the target PC into the calldests, and sets
     300             :    *opt_out_pc_hash to murmur3_32(target_pc) (if opt_out_pc_hash is
     301             :    non-NULL). Returns FD_SBPF_ELF_ERR_SYMBOL_HASH_COLLISION on failure
     302             :    if the target PC is already in the syscalls registry and leaves
     303             :    out_pc_hash in an undefined state.
     304             : 
     305             :    An important note is that Agave's implementation uses a map to store
     306             :    key-value pairs of (murmur3_32(target_pc), target_pc) within the
     307             :    calldests. We optimize this by using a set containing
     308             :    target_pc (this is our calldests map), and then deriving
     309             :    the target PC on the fly given murmur3_32(target_pc) (provided as
     310             :    imm) in the VM by computing the inverse hash (since murmur3_32 is
     311             :    bijective for uints).
     312             : 
     313             :    Another important note is that if a key-value pair already exists in
     314             :    Agave's calldests map, they will only throw a symbol hash collision
     315             :    error if the target PC is different from the one already registered.
     316             :    We can omit this check because of the hash function's bijective
     317             :    property, since the key-value pairs are deterministically derived
     318             :    from one another.
     319             : 
     320             :    TODO: this function will have to be adapted to hash the target PC
     321             :    depending on the SBPF version (>= V3). That has not been implemented
     322             :    yet.
     323             : 
     324             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/program.rs#L142-L178 */
     325             : static int
     326             : fd_sbpf_register_function_hashed_legacy( fd_sbpf_loader_t *  loader,
     327             :                                          fd_sbpf_program_t * prog,
     328             :                                          uchar const *       name,
     329             :                                          ulong               name_len,
     330             :                                          ulong               target_pc,
     331     3440039 :                                          uint *              opt_out_pc_hash ) {
     332             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/program.rs#L156-L160 */
     333     3440039 :   uint pc_hash;
     334     3440039 :   uchar is_entrypoint = fd_sbpf_slice_cstr_eq( name, name_len, "entrypoint" ) ||
     335     3440039 :                         target_pc==FD_SBPF_ENTRYPOINT_PC;
     336     3440039 :   if( FD_UNLIKELY( is_entrypoint ) ) {
     337       10912 :     if( FD_UNLIKELY( prog->entry_pc!=ULONG_MAX && prog->entry_pc!=target_pc  ) ) {
     338             :       /* We already registered the entrypoint to a different target PC,
     339             :          so we cannot register it again. */
     340           1 :       return FD_SBPF_ELF_ERR_SYMBOL_HASH_COLLISION;
     341           1 :     }
     342       10911 :     prog->entry_pc = target_pc;
     343             : 
     344             :     /* Optimization for this constant value */
     345       10911 :     pc_hash = FD_SBPF_ENTRYPOINT_HASH;
     346     3429127 :   } else {
     347     3429127 :     pc_hash = fd_pchash( (uint)target_pc );
     348     3429127 :   }
     349             : 
     350             :   /* loader.get_function_registry() is their equivalent of our syscalls
     351             :      registry. Fail if the target PC is present there.
     352             : 
     353             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/program.rs#L161-L163 */
     354     3440038 :   if( FD_UNLIKELY( fd_sbpf_syscalls_query( loader->syscalls, pc_hash, NULL ) ) ) {
     355           0 :     return FD_SBPF_ELF_ERR_SYMBOL_HASH_COLLISION;
     356           0 :   }
     357             : 
     358             :   /* Insert the target PC into the calldests set if it's not the
     359             :      entrypoint.  Due to the nature of our calldests, we also want to
     360             :      make sure that target_pc <= calldests_max, the call destination is
     361             :      guaranteed not a valid program counter (therefore does not need to
     362             :      be registered). */
     363     3440038 :   if( FD_LIKELY( !is_entrypoint &&
     364     3440038 :                  loader->calldests &&
     365     3453160 :                  fd_sbpf_calldests_valid_idx( loader->calldests, target_pc ) ) ) {
     366     3453160 :     fd_sbpf_calldests_insert( loader->calldests, target_pc );
     367     3453160 :   }
     368             : 
     369     3450488 :   if( opt_out_pc_hash ) *opt_out_pc_hash = pc_hash;
     370     3440038 :   return FD_SBPF_ELF_SUCCESS;
     371     3440038 : }
     372             : 
     373             : /* ELF Dynamic Relocations *********************************************
     374             : 
     375             :    ### Summary
     376             : 
     377             :    The sBPF ELF loader provides a limited dynamic relocation mechanism
     378             :    to fix up Clang-generated shared objects for execution in an sBPF VM.
     379             : 
     380             :    The relocation types themselves violate the eBPF and ELF specs in
     381             :    various ways.  In short, the relocation table (via DT_REL) is used to
     382             :    shift program code from zero-based addressing to the MM_PROGRAM
     383             :    segment in the VM memory map (at 0x1_0000_0000).
     384             : 
     385             :    As part of the Solana VM protocol it abides by strict determinism
     386             :    requirements.  This sadly means that we will have to replicate all
     387             :    edge cases and bugs in the Solana Labs ELF loader.
     388             : 
     389             :    Three relocation types are currently supported:
     390             :      - R_BPF_64_64: Sets an absolute address of a symbol as the
     391             :        64-bit immediate field of an lddw instruction
     392             :      - R_BPF_64_RELATIVE: Adds MM_PROGRAM_START (0x1_0000_0000) to ...
     393             :        a) ... the 64-bit imm field of an lddw instruction (if in text)
     394             :        b) ... a 64-bit integer (if not in text section)
     395             :      - R_BPF_64_32: Sets the 32-bit immediate field of a call
     396             :        instruction to ...
     397             :        a) the ID of a local function (Murmur3 hash of function PC address)
     398             :        b) the ID of a syscall
     399             : 
     400             :    Obviously invalid relocations (e.g. out-of-bounds of ELF file or
     401             :    unsupported reloc type) raise an error.
     402             :    Relocations that would corrupt ELF data structures are silently
     403             :    ignored (using the fd_sbpf_reloc_mask mechanism).
     404             : 
     405             :    ### History
     406             : 
     407             :    The use of relocations is technically redundant, as the Solana VM
     408             :    memory map has been hardcoded in program runtime v1 (so far the only
     409             :    runtime).  However, virtually all deployed programs as of April 2023
     410             :    are position-independent shared objects and make heavy use of such
     411             :    relocations.
     412             : 
     413             :    Relocations in the Solana VM have a complicated history.  Over the
     414             :    course of years, multiple protocol bugs have been added and fixed.
     415             :    The ELF loader needs to handle all these edge cases to avoid breaking
     416             :    "userspace".  I.e. any deployed programs which might be immutable
     417             :    must continue to function.
     418             : 
     419             :    While this complex logic will probably stick around for the next few
     420             :    years, the Solana protocol is getting increasingly restrictive for
     421             :    newly deployed ELFs.  Another proposed change is upgrading to
     422             :    position-dependent binaries without any dynamic relocations. */
     423             : 
     424             : /* R_BPF_64_64 relocates an absolute address into the extended imm field
     425             :    of an lddw-form instruction.  (Two instruction slots, low 32 bits in
     426             :    first immediate field, high 32 bits in second immediate field)
     427             : 
     428             :     Bits  0..32    32..64   64..96   96..128
     429             :          [ ... ] [ IMM_LO ] [ ... ] [ IMM_HI ]
     430             : 
     431             :     Returns 0 on success and writes the imm offset to the rodata.
     432             :     Returns the error code on failure.
     433             : 
     434             :     https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1069-L1141 */
     435             : 
     436             : static int
     437             : fd_sbpf_r_bpf_64_64( fd_sbpf_elf_t const *      elf,
     438             :                      ulong                      elf_sz,
     439             :                      uchar                    * rodata,
     440             :                      fd_sbpf_elf_info_t const * info,
     441             :                      fd_elf64_rel       const * dt_rel,
     442         206 :                      ulong                      r_offset ) {
     443             : 
     444         206 :   fd_elf64_shdr const * shdrs = (fd_elf64_shdr const *)( elf->bin + elf->ehdr.e_shoff );
     445             : 
     446             :   /* Note that the sbpf_version variable is ALWAYS V0 (see Agave's code
     447             :      to understand why).
     448             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1070-L1080 */
     449         206 :   ulong imm_offset = fd_ulong_sat_add( r_offset, 4UL /* BYTE_OFFSET_IMMEDIATE */ );
     450             : 
     451             :   /* Bounds check.
     452             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1084-L1086 */
     453         206 :   if( FD_UNLIKELY( fd_ulong_sat_add( imm_offset, 4UL /* BYTE_LENGTH_IMMEDIATE */ )>elf_sz ) ) {
     454           1 :     return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     455           1 :   }
     456             : 
     457             :   /* Get the symbol entry from the dynamic symbol table.
     458             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1089-L1092 */
     459         205 :   fd_elf64_sym const * symbol = NULL;
     460         205 :   {
     461             :     /* Ensure the dynamic symbol table exists. */
     462         205 :     if( FD_UNLIKELY( info->shndx_dynsymtab<0 ) ) {
     463           2 :       return FD_SBPF_ELF_ERR_UNKNOWN_SYMBOL;
     464           2 :     }
     465             : 
     466             :     /* Get the dynamic symbol table section header. The section header
     467             :        was already validated in fd_sbpf_lenient_elf_parse() so we can
     468             :        directly get the symbol table. */
     469         203 :     fd_elf64_shdr const * sh_dynsym    = &shdrs[ info->shndx_dynsymtab ];
     470         203 :     fd_elf64_sym const *  dynsym_table = (fd_elf64_sym const *)( elf->bin + sh_dynsym->sh_offset );
     471         203 :     ulong                 dynsym_cnt   = (ulong)(sh_dynsym->sh_size / sizeof(fd_elf64_sym));
     472             : 
     473             :     /* The symbol table index is stored in the lower 4 bytes of r_info.
     474             :        Check the bounds of the symbol table index. */
     475         203 :     ulong r_sym = FD_ELF64_R_SYM( dt_rel->r_info );
     476         203 :     if( FD_UNLIKELY( r_sym>=dynsym_cnt ) ) {
     477           1 :       return FD_SBPF_ELF_ERR_UNKNOWN_SYMBOL;
     478           1 :     }
     479         202 :     symbol = &dynsym_table[ r_sym ];
     480         202 :   }
     481             : 
     482             :   /* Use the relative address as an offset to derive the relocated
     483             :      address.
     484             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1094-L1096 */
     485         202 :   uint  refd_addr = FD_LOAD( uint, &rodata[ imm_offset ] );
     486         202 :   ulong addr      = fd_ulong_sat_add( symbol->st_value, refd_addr );
     487             : 
     488             :   /* We need to normalize the address into the VM's memory space, which
     489             :      is rooted at 0x1_0000_0000 (the program ro-data region). If the
     490             :      linker hasn't normalized the addresses already, we treat addr as
     491             :      a relative offset into the program ro-data region. */
     492         202 :   if( addr<FD_SBPF_MM_PROGRAM_ADDR ) {
     493         190 :     addr = fd_ulong_sat_add( addr, FD_SBPF_MM_PROGRAM_ADDR );
     494         190 :   }
     495             : 
     496             :   /* Again, no need to check the sbpf_version because it's always V0.
     497             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1106-L1140 */
     498         202 :   ulong imm_low_offset  = imm_offset;
     499         202 :   ulong imm_high_offset = fd_ulong_sat_add( imm_low_offset, 8UL /* INSN_SIZE */ );
     500             : 
     501             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1116-L1122 */
     502         202 :   {
     503             :     /* Bounds check before writing to the rodata. */
     504         202 :     if( FD_UNLIKELY( fd_ulong_sat_add( imm_low_offset, 4UL /* BYTE_LENGTH_IMMEDIATE */ )>elf_sz ) ) {
     505           0 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     506           0 :     }
     507             : 
     508             :     /* Write back */
     509         202 :     FD_STORE( uint, rodata+imm_low_offset, (uint)addr );
     510         202 :   }
     511             : 
     512             :   /* Same as above, but for the imm high offset.
     513             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1125-L1134 */
     514           0 :   {
     515             :     /* Bounds check before writing to the rodata. */
     516         202 :     if( FD_UNLIKELY( fd_ulong_sat_add( imm_high_offset, 4UL /* BYTE_LENGTH_IMMEDIATE */ )>elf_sz ) ) {
     517           0 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     518           0 :     }
     519             : 
     520             :     /* Write back */
     521         202 :     FD_STORE( uint, rodata+imm_high_offset, (uint)(addr>>32UL) );
     522         202 :   }
     523             : 
     524             :   /* ...rest of this function is a no-op because
     525             :      enable_symbol_and_section_labels is disabled in production. */
     526             : 
     527         202 :   return FD_SBPF_ELF_SUCCESS;
     528         202 : }
     529             : 
     530             : /* R_BPF_64_RELATIVE is almost entirely Solana specific. Returns 0 on
     531             :    success and an ElfError on failure.
     532             : 
     533             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1142-L1247 */
     534             : 
     535             : static int
     536             : fd_sbpf_r_bpf_64_relative( fd_sbpf_elf_t const *      elf,
     537             :                            ulong                      elf_sz,
     538             :                            uchar                    * rodata,
     539             :                            fd_sbpf_elf_info_t const * info,
     540     3213756 :                            ulong                      r_offset ) {
     541             : 
     542     3213756 :   fd_elf64_shdr const * shdrs   = (fd_elf64_shdr const *)( elf->bin + elf->ehdr.e_shoff );
     543     3213756 :   fd_elf64_shdr const * sh_text = &shdrs[ info->shndx_text ];
     544             : 
     545             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1147-L1148 */
     546     3213756 :   ulong imm_offset = fd_ulong_sat_add( r_offset, 4UL /* BYTE_OFFSET_IMMEDIATE */ );
     547             : 
     548             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1150-L1246 */
     549     3213756 :   fd_sbpf_range_t text_section_range;
     550     3213756 :   if( fd_shdr_get_file_range( sh_text, &text_section_range ) &&
     551     3213756 :       fd_sbpf_range_contains( &text_section_range, r_offset ) ) {
     552             : 
     553             :     /* We are relocating a lddw (load double word) instruction which
     554             :        spans two instruction slots. The address top be relocated is
     555             :        split in two halves in the two imms of the instruction slots.
     556             : 
     557             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1159-L1162 */
     558     2426897 :     ulong imm_low_offset  = imm_offset;
     559     2426897 :     ulong imm_high_offset = fd_ulong_sat_add( r_offset,
     560     2426897 :                                               4UL /* BYTE_OFFSET_IMMEDIATE */ + 8UL /* INSN_SIZE */ );
     561             : 
     562             :     /* Read the low side of the address. Perform a bounds check first.
     563             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1164-L1171 */
     564     2426897 :     if( FD_UNLIKELY( fd_ulong_sat_add( imm_low_offset, 4UL /* BYTE_LENGTH_IMMEDIATE */ )>elf_sz ) ) {
     565           0 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     566           0 :     }
     567     2426897 :     uint va_low = FD_LOAD( uint, rodata+imm_low_offset );
     568             : 
     569             :     /* Read the high side of the address. Perform a bounds check first.
     570             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1174-L1180 */
     571     2426897 :     if( FD_UNLIKELY( fd_ulong_sat_add( imm_high_offset, 4UL /* BYTE_LENGTH_IMMEDIATE */ )>elf_sz ) ) {
     572           1 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     573           1 :     }
     574     2426896 :     uint va_high = FD_LOAD( uint, rodata+imm_high_offset );
     575             : 
     576             :     /* Put the address back together.
     577             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1182-L1187 */
     578     2426896 :     ulong refd_addr = ( (ulong)va_high<<32UL ) | va_low;
     579     2426896 :     if( FD_UNLIKELY( refd_addr==0UL ) ) {
     580          10 :       return FD_SBPF_ELF_ERR_INVALID_VIRTUAL_ADDRESS;
     581          10 :     }
     582             : 
     583             :     /* We need to normalize the address into the VM's memory space, which
     584             :        is rooted at 0x1_0000_0000 (the program ro-data region). If the
     585             :        linker hasn't normalized the addresses already, we treat addr as
     586             :        a relative offset into the program ro-data region.
     587             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1189-L1193 */
     588     2426886 :     if( refd_addr<FD_SBPF_MM_PROGRAM_ADDR ) {
     589     2421472 :       refd_addr = fd_ulong_sat_add( refd_addr, FD_SBPF_MM_PROGRAM_ADDR );
     590     2421472 :     }
     591             : 
     592             :     /* Write back the low half. Perform a bounds check first.
     593             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1195-L1202 */
     594     2426886 :     if( FD_UNLIKELY( fd_ulong_sat_add( imm_low_offset, 4UL /* BYTE_LENGTH_IMMEDIATE */ )>elf_sz ) ) {
     595           0 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     596           0 :     }
     597     2426886 :     FD_STORE( uint, rodata+imm_low_offset, (uint)refd_addr );
     598             : 
     599             :     /* Write back the high half. Perform a bounds check first.
     600             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1205-L1214 */
     601     2426886 :     if( FD_UNLIKELY( fd_ulong_sat_add( imm_high_offset, 4UL /* BYTE_LENGTH_IMMEDIATE */ )>elf_sz ) ) {
     602           0 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     603           0 :     }
     604     2426886 :     FD_STORE( uint, rodata+imm_high_offset, (uint)(refd_addr>>32UL) );
     605     2426886 :   } else {
     606             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1216-L1228 */
     607      786859 :     ulong refd_addr = 0UL;
     608             : 
     609             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1230-L1239 */
     610      786859 :     if( FD_UNLIKELY( fd_ulong_sat_add( imm_offset, 4UL /* BYTE_LENGTH_IMMEDIATE */ )>elf_sz ) ) {
     611           3 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     612           3 :     }
     613      786856 :     refd_addr = FD_LOAD( uint, rodata+imm_offset );
     614      786856 :     refd_addr = fd_ulong_sat_add( refd_addr, FD_SBPF_MM_PROGRAM_ADDR );
     615             : 
     616             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1242-L1245 */
     617      786856 :     if( FD_UNLIKELY( fd_ulong_sat_add( r_offset, sizeof(ulong) )>elf_sz ) ) {
     618           0 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     619           0 :     }
     620             : 
     621      786856 :     FD_STORE( ulong, rodata+r_offset, refd_addr );
     622      786856 :   }
     623             : 
     624     3213742 :   return FD_SBPF_ELF_SUCCESS;
     625     3213756 : }
     626             : 
     627             : /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1248-L1301 */
     628             : static int
     629             : fd_sbpf_r_bpf_64_32( fd_sbpf_loader_t *              loader,
     630             :                      fd_sbpf_program_t *             prog,
     631             :                      fd_sbpf_elf_t const *           elf,
     632             :                      ulong                           elf_sz,
     633             :                      uchar *                         rodata,
     634             :                      fd_sbpf_elf_info_t const *      info,
     635             :                      fd_elf64_rel const *            dt_rel,
     636             :                      ulong                           r_offset,
     637      603344 :                      fd_sbpf_loader_config_t const * config ) {
     638             : 
     639      603344 :   fd_elf64_shdr const * shdrs   = (fd_elf64_shdr const *)( elf->bin + elf->ehdr.e_shoff );
     640      603344 :   fd_elf64_shdr const * sh_text = &shdrs[ info->shndx_text ];
     641             : 
     642             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1253-L1254 */
     643      603344 :   ulong imm_offset = fd_ulong_sat_add( r_offset, 4UL /* BYTE_OFFSET_IMMEDIATE */ );
     644             : 
     645             :   /* Get the symbol entry from the dynamic symbol table.
     646             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1256-L1259 */
     647      603344 :   fd_elf64_sym const * symbol = NULL;
     648             : 
     649             :   /* Ensure the dynamic symbol table exists. */
     650      603344 :   if( FD_UNLIKELY( info->shndx_dynsymtab<0 ) ) {
     651           2 :     return FD_SBPF_ELF_ERR_UNKNOWN_SYMBOL;
     652           2 :   }
     653             : 
     654             :   /* Get the dynamic symbol table section header. The section header
     655             :      was already validated in fd_sbpf_lenient_elf_parse() so we can
     656             :      directly get the symbol table. */
     657      603342 :   fd_elf64_shdr const * sh_dynsym    = &shdrs[ info->shndx_dynsymtab ];
     658      603342 :   fd_elf64_sym const *  dynsym_table = (fd_elf64_sym const *)( elf->bin + sh_dynsym->sh_offset );
     659      603342 :   ulong                 dynsym_cnt   = (ulong)(sh_dynsym->sh_size / sizeof(fd_elf64_sym));
     660             : 
     661             :   /* The symbol table index is stored in the lower 4 bytes of r_info.
     662             :      Check the bounds of the symbol table index. */
     663      603342 :   ulong r_sym = FD_ELF64_R_SYM( dt_rel->r_info );
     664      603342 :   if( FD_UNLIKELY( r_sym>=dynsym_cnt ) ) {
     665           1 :     return FD_SBPF_ELF_ERR_UNKNOWN_SYMBOL;
     666           1 :   }
     667      603341 :   symbol = &dynsym_table[ r_sym ];
     668             : 
     669             :   /* Verify symbol name.
     670             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1261-L1263
     671             : 
     672             :      First check if the dynamic string table exists:
     673             :      If the dynamic string table does not exist then dynamic_symbol_name()
     674             :      will throw an error because
     675             : 
     676             :      self.dynamic_symbol_names_section_header
     677             :        .ok_or(ElfParserError::NoDynamicStringTable)?
     678             : 
     679             :      will throw an error which, will be mapped to UnknownSymbol
     680             :      https://github.com/anza-xyz/sbpf/blob/main/src/elf_parser/mod.rs#L528-L536 */
     681      603341 :   if( FD_UNLIKELY( info->shndx_dynstr<0 ) ) {
     682           4 :     return FD_SBPF_ELF_ERR_UNKNOWN_SYMBOL;
     683           4 :   }
     684             : 
     685      603337 :   uchar const *         name;
     686      603337 :   ulong                 name_len;
     687      603337 :   fd_elf64_shdr const * dyn_section_names_shdr = &shdrs[ info->shndx_dynstr ];
     688      603337 :   if( FD_UNLIKELY( fd_sbpf_lenient_get_string_in_section( elf->bin, elf_sz, dyn_section_names_shdr, symbol->st_name, FD_SBPF_SYMBOL_NAME_SZ_MAX, &name, &name_len ) ) ) {
     689           4 :     return FD_SBPF_ELF_ERR_UNKNOWN_SYMBOL;
     690           4 :   }
     691             : 
     692             :   /* If the symbol is defined, this is a bpf-to-bpf call.
     693             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1265-L1295 */
     694      603333 :   uint key = 0U;
     695      603333 :   int symbol_is_function = ( FD_ELF64_ST_TYPE( symbol->st_info )==FD_ELF_STT_FUNC );
     696      603333 :   {
     697      603333 :     if( symbol_is_function && symbol->st_value!=0UL ) {
     698             :       /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1267-L1269 */
     699       18490 :       fd_sbpf_range_t text_section_range = (fd_sbpf_range_t) {
     700       18490 :           .lo = sh_text->sh_addr,
     701       18490 :           .hi = fd_ulong_sat_add( sh_text->sh_addr, sh_text->sh_size ) };
     702       18490 :       if( FD_UNLIKELY( !fd_sbpf_range_contains( &text_section_range, symbol->st_value ) ) ) {
     703           2 :         return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     704           2 :       }
     705             : 
     706             :       /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1270-L1279 */
     707       18488 :       ulong target_pc = fd_ulong_sat_sub( symbol->st_value, sh_text->sh_addr ) / 8UL;
     708       18488 :       int err = fd_sbpf_register_function_hashed_legacy( loader, prog, name, name_len, target_pc, &key );
     709       18488 :       if( FD_UNLIKELY( err!=FD_SBPF_ELF_SUCCESS ) ) {
     710           1 :         return err;
     711           1 :       }
     712      584843 :     } else {
     713             :       /* Else, it's a syscall. Ensure that the syscall can be resolved.
     714             :          https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1281-L1294 */
     715      584843 :       key = fd_murmur3_32(name, name_len, 0UL );
     716      584843 :       if( FD_UNLIKELY( config->reject_broken_elfs &&
     717      584843 :                        fd_sbpf_syscalls_query( loader->syscalls, key, NULL )==NULL ) ) {
     718          15 :         return FD_SBPF_ELF_ERR_UNRESOLVED_SYMBOL;
     719          15 :       }
     720      584843 :     }
     721      603333 :   }
     722             : 
     723             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1297-L1300 */
     724      603315 :   if( FD_UNLIKELY( fd_ulong_sat_add( imm_offset, 4UL /* BYTE_LENGTH_IMMEDIATE */ )>elf_sz ) ) {
     725           6 :     return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
     726           6 :   }
     727             : 
     728      603309 :   FD_STORE( uint, rodata+imm_offset, key );
     729             : 
     730      603309 :   return FD_SBPF_ELF_SUCCESS;
     731      603315 : }
     732             : 
     733             : static int
     734             : fd_sbpf_elf_peek_strict( fd_sbpf_elf_info_t * info,
     735             :                          void const *         bin,
     736           0 :                          ulong                bin_sz ) {
     737             : 
     738             :   /* Parse file header */
     739             : 
     740             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L425
     741             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L278
     742             :      (Agave does some extra checks on alignment, but they don't seem necessary) */
     743           0 :   if( FD_UNLIKELY( bin_sz<sizeof(fd_elf64_ehdr) ) ) {
     744           0 :     return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     745           0 :   }
     746             : 
     747           0 :   fd_elf64_ehdr ehdr = FD_LOAD( fd_elf64_ehdr, bin );
     748             : 
     749             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L430-L453 */
     750           0 :   ulong program_header_table_end = fd_ulong_sat_add( sizeof(fd_elf64_ehdr), fd_ulong_sat_mul( ehdr.e_phnum, sizeof(fd_elf64_phdr) ) );
     751             : 
     752           0 :   int parse_ehdr_err =
     753           0 :       ( fd_uint_load_4( ehdr.e_ident )    != FD_ELF_MAG_LE         )
     754           0 :     | ( ehdr.e_ident[ FD_ELF_EI_CLASS   ] != FD_ELF_CLASS_64       )
     755           0 :     | ( ehdr.e_ident[ FD_ELF_EI_DATA    ] != FD_ELF_DATA_LE        )
     756           0 :     | ( ehdr.e_ident[ FD_ELF_EI_VERSION ] != 1                     )
     757           0 :     | ( ehdr.e_ident[ FD_ELF_EI_OSABI   ] != FD_ELF_OSABI_NONE     )
     758             :     // The 7 padding bytes [9, 16) must be 0. Byte 8 (EI_OSABI) is 0 due to above check, so check [8, 16).
     759           0 :     | ( fd_ulong_load_8( ehdr.e_ident+8 ) != 0UL                   )
     760           0 :     | ( ehdr.e_type                       != FD_ELF_ET_DYN         )
     761           0 :     | ( ehdr.e_machine                    != FD_ELF_EM_SBPF        )
     762           0 :     | ( ehdr.e_version                    != 1                     )
     763             :     // | ( ehdr.e_entry )
     764           0 :     | ( ehdr.e_phoff                      != sizeof(fd_elf64_ehdr) )
     765             :     // | ( ehdr.e_shoff )
     766             :     // | ( ehdr.e_flags )
     767           0 :     | ( ehdr.e_ehsize                     != sizeof(fd_elf64_ehdr) )
     768           0 :     | ( ehdr.e_phentsize                  != sizeof(fd_elf64_phdr) )
     769           0 :     | ( ehdr.e_phnum                      <  EXPECTED_PHDR_CNT     ) /* SIMD-0189 says < instead of != */
     770           0 :     | ( program_header_table_end          >= bin_sz                )
     771           0 :     | ( ehdr.e_shentsize                  != sizeof(fd_elf64_shdr) )
     772             :     // | ( ehdr.e_shnum )
     773           0 :     | ( ehdr.e_shstrndx                   >= ehdr.e_shnum          )
     774           0 :   ;
     775           0 :   if( FD_UNLIKELY( parse_ehdr_err ) ) {
     776           0 :     return FD_SBPF_ELF_PARSER_ERR_INVALID_FILE_HEADER;
     777           0 :   }
     778             : 
     779             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L462 */
     780           0 :   if( FD_UNLIKELY( (program_header_table_end-sizeof(fd_elf64_ehdr))%sizeof(fd_elf64_phdr) ) ) {
     781           0 :     return FD_SBPF_ELF_PARSER_ERR_INVALID_SIZE;
     782           0 :   }
     783           0 :   if( FD_UNLIKELY( program_header_table_end>bin_sz ) ) {
     784           0 :     return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     785           0 :   }
     786             :   /* This is always true ... */
     787             :   // if( FD_UNLIKELY( !fd_ulong_is_aligned( sizeof(fd_elf64_ehdr), 8UL ) ) ) {
     788             :   //   return FD_SBPF_ELF_PARSER_ERR_INVALID_ALIGNMENT;
     789             :   // }
     790             : 
     791             :   /* Parse program headers (expecting 4 segments) */
     792             : 
     793             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L455-L487
     794             :      Note: Agave iterates with a zip, i.e. it cuts the loop to 4, even
     795             :            though the number of phdrs is allowed to be higher. */
     796           0 :   ulong expected_p_vaddr[ EXPECTED_PHDR_CNT ] = { FD_SBPF_MM_BYTECODE_ADDR, FD_SBPF_MM_RODATA_ADDR, FD_SBPF_MM_STACK_ADDR, FD_SBPF_MM_HEAP_ADDR };
     797           0 :   uint  expected_p_flags[ EXPECTED_PHDR_CNT ] = { FD_SBPF_PF_X,             FD_SBPF_PF_R,           FD_SBPF_PF_RW,         FD_SBPF_PF_RW        };
     798           0 :   fd_elf64_phdr     phdr[ EXPECTED_PHDR_CNT ];
     799           0 :   for( uint i=0; i<EXPECTED_PHDR_CNT; i++ ) {
     800           0 :     ulong phdr_off = sizeof(fd_elf64_ehdr) + i*sizeof(fd_elf64_phdr);
     801           0 :     phdr[ i ] = FD_LOAD( fd_elf64_phdr, bin+phdr_off );
     802             : 
     803           0 :     ulong p_filesz = ( expected_p_flags[ i ] & FD_SBPF_PF_W ) ? 0UL : phdr[ i ].p_memsz;
     804           0 :     int parse_phdr_err =
     805           0 :         ( phdr[ i ].p_type         != FD_ELF_PT_LOAD              )
     806           0 :       | ( phdr[ i ].p_flags        != expected_p_flags[ i ]       )
     807           0 :       | ( phdr[ i ].p_offset       <  program_header_table_end    )
     808           0 :       | ( phdr[ i ].p_offset       >= bin_sz                      )
     809           0 :       | ( phdr[ i ].p_offset % 8UL != 0UL                         )
     810           0 :       | ( phdr[ i ].p_vaddr        != expected_p_vaddr[ i ]       )
     811           0 :       | ( phdr[ i ].p_paddr        != expected_p_vaddr[ i ]       )
     812           0 :       | ( phdr[ i ].p_filesz       != p_filesz                    )
     813           0 :       | ( phdr[ i ].p_filesz       >  bin_sz - phdr[ i ].p_offset )
     814           0 :       | ( phdr[ i ].p_filesz % 8UL != 0UL                         )
     815           0 :       | ( phdr[ i ].p_memsz        >= FD_SBPF_MM_REGION_SZ        )
     816           0 :     ;
     817           0 :     if( FD_UNLIKELY( parse_phdr_err ) ) {
     818           0 :       return FD_SBPF_ELF_PARSER_ERR_INVALID_PROGRAM_HEADER;
     819           0 :     }
     820           0 :   }
     821             : 
     822             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L489-L506 */
     823           0 :   ulong vm_range_start = phdr[ 0 ].p_vaddr;
     824           0 :   ulong vm_range_end = phdr[ 0 ].p_vaddr + phdr[ 0 ].p_memsz;
     825           0 :   ulong entry_chk = ehdr.e_entry + 7UL;
     826           0 :   int parse_e_entry_err =
     827           0 :      !( vm_range_start <= entry_chk && entry_chk < vm_range_end ) /* rust contains includes min, excludes max*/
     828           0 :     | ( ehdr.e_entry % 8UL != 0UL                               )
     829           0 :   ;
     830           0 :   if( FD_UNLIKELY( parse_e_entry_err ) ) {
     831           0 :     return FD_SBPF_ELF_PARSER_ERR_INVALID_FILE_HEADER;
     832           0 :   }
     833             : 
     834             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L507-L515 */
     835           0 :   ulong entry_pc = ( ehdr.e_entry - phdr[ 0 ].p_vaddr ) / 8UL;
     836           0 :   ulong insn = fd_ulong_load_8( (uchar const *) bin + phdr[ 0 ].p_offset + entry_pc*8UL );
     837             :   /* Entrypoint must be a valid function start (ADD64_IMM with dst=r10)
     838             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/ebpf.rs#L588 */
     839           0 :   if( FD_UNLIKELY( !fd_sbpf_is_function_start( fd_sbpf_instr( insn ) ) ) ) {
     840           0 :     return FD_SBPF_ELF_PARSER_ERR_INVALID_FILE_HEADER;
     841           0 :   }
     842             : 
     843             :   /* config.enable_symbol_and_section_labels is false in production,
     844             :      so there's nothing else to do.
     845             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L519 */
     846             : 
     847           0 :   info->bin_sz   = bin_sz;
     848           0 :   info->text_off = (uint)phdr[ 0 ].p_offset;
     849           0 :   info->text_sz  = (uint)phdr[ 0 ].p_memsz;
     850           0 :   info->text_cnt = (uint)( phdr[ 0 ].p_memsz / 8UL );
     851             : 
     852           0 :   return FD_SBPF_ELF_SUCCESS;
     853           0 : }
     854             : 
     855             : static inline int
     856      329330 : fd_sbpf_check_overlap( ulong a_start, ulong a_end, ulong b_start, ulong b_end ) {
     857      329330 :   return !( ( a_end <= b_start || b_end <= a_start ) );
     858      329330 : }
     859             : 
     860             : /* Mirrors Elf64::parse() in Agave. Returns an ElfParserError code on
     861             :    failure and 0 on success.
     862             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L148 */
     863             : int
     864             : fd_sbpf_lenient_elf_parse( fd_sbpf_elf_info_t * info,
     865             :                            void const *         bin,
     866       13457 :                            ulong                bin_sz ) {
     867             : 
     868             :   /* This documents the values that will be set in this function */
     869       13457 :   info->bin_sz          = bin_sz;
     870       13457 :   info->phndx_dyn       = -1;
     871       13457 :   info->shndx_dyn       = -1;
     872       13457 :   info->shndx_symtab    = -1;
     873       13457 :   info->shndx_strtab    = -1;
     874       13457 :   info->shndx_dynstr    = -1;
     875       13457 :   info->shndx_dynsymtab = -1;
     876             : 
     877             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L149 */
     878       13457 :   if( FD_UNLIKELY( bin_sz<sizeof(fd_elf64_ehdr) ) ) {
     879          97 :     return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     880          97 :   }
     881             : 
     882       13360 :   fd_elf64_ehdr ehdr = FD_LOAD( fd_elf64_ehdr, bin );
     883       13360 :   ulong ehdr_start = 0;
     884       13360 :   ulong ehdr_end = sizeof(fd_elf64_ehdr);
     885             : 
     886             :   /* ELF header
     887             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L151-L162 */
     888       13360 :   int parse_ehdr_err =
     889       13360 :       ( fd_uint_load_4( ehdr.e_ident )    != FD_ELF_MAG_LE         )
     890       13360 :     | ( ehdr.e_ident[ FD_ELF_EI_CLASS   ] != FD_ELF_CLASS_64       )
     891       13360 :     | ( ehdr.e_ident[ FD_ELF_EI_DATA    ] != FD_ELF_DATA_LE        )
     892       13360 :     | ( ehdr.e_ident[ FD_ELF_EI_VERSION ] != 1                     )
     893       13360 :     | ( ehdr.e_version                    != 1                     )
     894       13360 :     | ( ehdr.e_ehsize                     != sizeof(fd_elf64_ehdr) )
     895       13360 :     | ( ehdr.e_phentsize                  != sizeof(fd_elf64_phdr) )
     896       13360 :     | ( ehdr.e_shentsize                  != sizeof(fd_elf64_shdr) )
     897       13360 :     | ( ehdr.e_shstrndx                   >= ehdr.e_shnum          )
     898       13360 :   ;
     899       13360 :   if( FD_UNLIKELY( parse_ehdr_err ) ) {
     900        2187 :     return FD_SBPF_ELF_PARSER_ERR_INVALID_FILE_HEADER;
     901        2187 :   }
     902             : 
     903             :   /* Program headers
     904             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L164-L165 */
     905       11173 :   ulong phdr_start = ehdr.e_phoff;
     906       11173 :   ulong phdr_end, phdr_sz;
     907             :   /* Elf64::parse_program_header_table() */
     908       11173 :   {
     909       11173 :     if( FD_UNLIKELY( __builtin_umull_overflow( ehdr.e_phnum, sizeof(fd_elf64_phdr), &phdr_sz ) ) ) {
     910           0 :       return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     911           0 :     }
     912             : 
     913       11173 :     if( FD_UNLIKELY( __builtin_uaddl_overflow( ehdr.e_phoff, phdr_sz, &phdr_end ) ) ) {
     914             :       /* ArithmeticOverflow -> ElfParserError::OutOfBounds
     915             :         https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L671-L675 */
     916           0 :       return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     917           0 :     }
     918             : 
     919             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L301 */
     920       11173 :     if( FD_UNLIKELY( fd_sbpf_check_overlap( ehdr_start, ehdr_end, phdr_start, phdr_end ) ) ) {
     921           2 :       return FD_SBPF_ELF_PARSER_ERR_OVERLAP;
     922           2 :     }
     923             : 
     924             :     /* Ensure program header table range lies within the file, like
     925             :        slice_from_bytes. Unfortunately the checks have to be split up
     926             :        because Agave throws different error codes depending on which
     927             :        condition fails...
     928             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L302-L303 */
     929       11171 :     if( FD_UNLIKELY( phdr_sz%sizeof(fd_elf64_phdr)!=0UL ) ) {
     930           0 :       return FD_SBPF_ELF_PARSER_ERR_INVALID_SIZE;
     931           0 :     }
     932             : 
     933       11171 :     if( FD_UNLIKELY( phdr_end>bin_sz ) ) {
     934           5 :       return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     935           5 :     }
     936             : 
     937       11166 :     if( FD_UNLIKELY( !fd_ulong_is_aligned( phdr_start, 8UL ) ) ) {
     938           1 :       return FD_SBPF_ELF_PARSER_ERR_INVALID_ALIGNMENT;
     939           1 :     }
     940       11166 :   }
     941             : 
     942             :   /* Section headers
     943             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L167-L172 */
     944             : 
     945       11165 :   ulong shdr_start = ehdr.e_shoff;
     946       11165 :   ulong shdr_end, shdr_sz;
     947             :   /* Elf64::parse_section_header_table() */
     948       11165 :   {
     949       11165 :     if( FD_UNLIKELY( __builtin_umull_overflow( ehdr.e_shnum, sizeof(fd_elf64_shdr), &shdr_sz ) ) ) {
     950           0 :       return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     951           0 :     }
     952             : 
     953             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L314-L317 */
     954       11165 :     if( FD_UNLIKELY( __builtin_uaddl_overflow( ehdr.e_shoff, shdr_sz, &shdr_end ) ) ) {
     955             :       /* ArithmeticOverflow -> ElfParserError::OutOfBounds
     956             :         https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L671-L675 */
     957           0 :       return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     958           0 :     }
     959             : 
     960             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L318 */
     961       11165 :     if( FD_UNLIKELY( fd_sbpf_check_overlap( ehdr_start, ehdr_end, shdr_start, shdr_end ) ) ) {
     962           0 :       return FD_SBPF_ELF_PARSER_ERR_OVERLAP;
     963           0 :     }
     964             : 
     965             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L319 */
     966       11165 :     if( FD_UNLIKELY( fd_sbpf_check_overlap( phdr_start, phdr_end, shdr_start, shdr_end ) ) ) {
     967           1 :       return FD_SBPF_ELF_PARSER_ERR_OVERLAP;
     968           1 :     }
     969             : 
     970             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L321 */
     971       11164 :     if( FD_UNLIKELY( (shdr_end-ehdr.e_shoff)%sizeof(fd_elf64_shdr) ) ) {
     972           0 :       return FD_SBPF_ELF_PARSER_ERR_INVALID_SIZE;
     973           0 :     }
     974             : 
     975             :     /* Ensure section header table range lies within the file, like slice_from_bytes */
     976       11164 :     if( FD_UNLIKELY( shdr_end > bin_sz ) ) {
     977           2 :       return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
     978           2 :     }
     979             : 
     980       11162 :     if( FD_UNLIKELY( !fd_ulong_is_aligned( ehdr.e_shoff, 8UL ) ) ) {
     981           4 :       return FD_SBPF_ELF_PARSER_ERR_INVALID_ALIGNMENT;
     982           4 :     }
     983       11162 :   }
     984             : 
     985             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L174-L177 */
     986       11158 :   fd_elf64_shdr shdr = FD_LOAD( fd_elf64_shdr, bin + ehdr.e_shoff );
     987       11158 :   if( FD_UNLIKELY( shdr.sh_type != FD_ELF_SHT_NULL ) ) {
     988           1 :     return FD_SBPF_ELF_PARSER_ERR_INVALID_SECTION_HEADER;
     989           1 :   }
     990             : 
     991             :   /* Parse each program header
     992             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L179-L196 */
     993       11157 :   ulong vaddr = 0UL;
     994       49483 :   for( ulong i=0; i<ehdr.e_phnum; i++ ) {
     995       38333 :     fd_elf64_phdr phdr = FD_LOAD( fd_elf64_phdr, bin + phdr_start + i*sizeof(fd_elf64_phdr) );
     996       38333 :     if( FD_UNLIKELY( phdr.p_type != FD_ELF_PT_LOAD ) ) {
     997             :       /* Remember first PT_DYNAMIC program header for dynamic parsing */
     998       10268 :       if( phdr.p_type==FD_ELF_PT_DYNAMIC && info->phndx_dyn == -1 ) {
     999        9573 :         info->phndx_dyn = (int)i;
    1000        9573 :       }
    1001       10268 :       continue;
    1002       10268 :     }
    1003       28065 :     if( FD_UNLIKELY( phdr.p_vaddr<vaddr ) ) {
    1004           1 :       return FD_SBPF_ELF_PARSER_ERR_INVALID_PROGRAM_HEADER;
    1005           1 :     }
    1006       28064 :     ulong _offset_plus_size;
    1007       28064 :     if( FD_UNLIKELY( __builtin_uaddl_overflow( phdr.p_offset, phdr.p_filesz, &_offset_plus_size ) ) ) {
    1008           5 :       return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
    1009           5 :     }
    1010       28059 :     if( FD_UNLIKELY( phdr.p_offset + phdr.p_filesz > bin_sz ) ) {
    1011           1 :       return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
    1012           1 :     }
    1013       28058 :     vaddr = phdr.p_vaddr;
    1014       28058 :   }
    1015             : 
    1016             :   /* Parse each section header
    1017             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L198-L216 */
    1018       11150 :   ulong offset = 0UL;
    1019      110162 :   for( ulong i=0; i<ehdr.e_shnum; i++ ) {
    1020             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L200-L205 */
    1021       99031 :     fd_elf64_shdr shdr = FD_LOAD( fd_elf64_shdr, bin + shdr_start + i*sizeof(fd_elf64_shdr) );
    1022       99031 :     if( FD_UNLIKELY( shdr.sh_type==FD_ELF_SHT_NOBITS ) ) {
    1023         182 :       continue;
    1024         182 :     }
    1025             : 
    1026             :     /* Remember first SHT_DYNAMIC section header for dynamic parsing */
    1027       98849 :     if( shdr.sh_type==FD_ELF_SHT_DYNAMIC && info->shndx_dyn == -1 ) {
    1028       11055 :       info->shndx_dyn = (int)i;
    1029       11055 :     }
    1030             : 
    1031       98849 :     ulong sh_start = shdr.sh_offset;
    1032       98849 :     ulong sh_end;
    1033       98849 :     if( FD_UNLIKELY( __builtin_uaddl_overflow( shdr.sh_offset, shdr.sh_size, &sh_end ) ) ) {
    1034           2 :       return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
    1035           2 :     }
    1036             : 
    1037             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L206-L208 */
    1038       98847 :     if( FD_UNLIKELY( fd_sbpf_check_overlap( sh_start, sh_end, ehdr_start, ehdr_end ) ) ) {
    1039           2 :       return FD_SBPF_ELF_PARSER_ERR_OVERLAP;
    1040           2 :     }
    1041       98845 :     if( FD_UNLIKELY( fd_sbpf_check_overlap( sh_start, sh_end, phdr_start, phdr_end ) ) ) {
    1042           3 :       return FD_SBPF_ELF_PARSER_ERR_OVERLAP;
    1043           3 :     }
    1044       98842 :     if( FD_UNLIKELY( fd_sbpf_check_overlap( sh_start, sh_end, shdr_start, shdr_end ) ) ) {
    1045           1 :       return FD_SBPF_ELF_PARSER_ERR_OVERLAP;
    1046           1 :     }
    1047             : 
    1048             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L209-L215 */
    1049       98841 :     if( FD_UNLIKELY( sh_start < offset ) ) {
    1050           1 :       return FD_SBPF_ELF_PARSER_ERR_SECTION_NOT_IN_ORDER;
    1051           1 :     }
    1052       98840 :     offset = sh_end;
    1053       98840 :     if( FD_UNLIKELY( sh_end > bin_sz ) ) {
    1054          10 :       return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
    1055          10 :     }
    1056       98840 :   }
    1057             : 
    1058             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L218-L224
    1059             :      section_header_table.get() returning ok is equivalent to ehdr.e_shstrndx < ehdr.e_shnum,
    1060             :      and this is already checked above. So, nothing to do here. */
    1061             : 
    1062             :   /* Parse sections
    1063             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L240 */
    1064       11131 :   {
    1065             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L340-L342 */
    1066       11131 :     if( FD_UNLIKELY( ehdr.e_shstrndx == 0 ) ) {
    1067           0 :       return FD_SBPF_ELF_PARSER_ERR_NO_SECTION_NAME_STRING_TABLE;
    1068           0 :     }
    1069             : 
    1070             :     /* Use section name string table to identify well-known sections */
    1071       11131 :     ulong section_names_shdr_idx = ehdr.e_shstrndx;
    1072       11131 :     fd_elf64_shdr section_names_shdr = FD_LOAD( fd_elf64_shdr, bin + shdr_start + section_names_shdr_idx*sizeof(fd_elf64_shdr) );
    1073             :     /* Agave repeats the following validation all the times, we can do it once here
    1074             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L474-L476 */
    1075       11131 :     if( FD_UNLIKELY( section_names_shdr.sh_type != FD_ELF_SHT_STRTAB ) ) {
    1076           2 :       return FD_SBPF_ELF_PARSER_ERR_INVALID_SECTION_HEADER;
    1077           2 :     }
    1078             : 
    1079             :     /* Iterate sections and record indices for .text, .symtab, .strtab, .dyn, .dynstr */
    1080      108555 :     for( ulong i=0; i<ehdr.e_shnum; i++ ) {
    1081             :       /* Again... */
    1082       97439 :       fd_elf64_shdr shdr = FD_LOAD( fd_elf64_shdr, bin + shdr_start + i*sizeof(fd_elf64_shdr) );
    1083             : 
    1084       97439 :       uchar const * name;
    1085       97439 :       ulong         name_len;
    1086       97439 :       int res = fd_sbpf_lenient_get_string_in_section( bin, bin_sz, &section_names_shdr, shdr.sh_name, FD_SBPF_SECTION_NAME_SZ_MAX, &name, &name_len );
    1087       97439 :       if( FD_UNLIKELY( res < 0 ) ) {
    1088          10 :         return res;
    1089          10 :       }
    1090             : 
    1091             :       /* Store the first section by name:
    1092             :          https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L350-L355
    1093             :          The rust code expands in:
    1094             :             match section_name {
    1095             :                 b".symtab" => {
    1096             :                     if self.symbol_section_header.is_some() {
    1097             :                         return Err(ElfParserError::InvalidSectionHeader);
    1098             :                     }
    1099             :                     self.symbol_section_header = Some(section_header);
    1100             :                 }
    1101             :                 ...
    1102             :                 _ => {}
    1103             :             }
    1104             :          Note that the number of bytes compared should not include the
    1105             :          null-terminator.
    1106             :         */
    1107       97429 :       if( fd_sbpf_slice_cstr_eq( name, name_len, ".symtab" ) ) {
    1108        1771 :         if( FD_UNLIKELY( info->shndx_symtab != -1 ) ) {
    1109           1 :           return FD_SBPF_ELF_PARSER_ERR_INVALID_SECTION_HEADER;
    1110           1 :         }
    1111        1770 :         info->shndx_symtab = (int)i;
    1112       95658 :       } else if( fd_sbpf_slice_cstr_eq( name, name_len, ".strtab" ) ) {
    1113         256 :         if( FD_UNLIKELY( info->shndx_strtab != -1 ) ) {
    1114           1 :           return FD_SBPF_ELF_PARSER_ERR_INVALID_SECTION_HEADER;
    1115           1 :         }
    1116         255 :         info->shndx_strtab = (int)i;
    1117       95402 :       } else if( fd_sbpf_slice_cstr_eq( name, name_len, ".dynstr" ) ) {
    1118       10965 :         if( FD_UNLIKELY( info->shndx_dynstr != -1 ) ) {
    1119           1 :           return FD_SBPF_ELF_PARSER_ERR_INVALID_SECTION_HEADER;
    1120           1 :         }
    1121       10964 :         info->shndx_dynstr = (int)i;
    1122       10964 :       }
    1123       97429 :     }
    1124       11129 :   }
    1125             : 
    1126             :   /* Parse dynamic
    1127             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L241 */
    1128       11116 :   {
    1129             :     /* Try PT_DYNAMIC first; if invalid or absent, fall back to SHT_DYNAMIC.
    1130             :        Note that only the first PT_DYNAMIC and SHT_DYNAMIC are used because of Rust iter().find().
    1131             :        Mirrors Rust logic:
    1132             :          - Try PT_DYNAMIC: https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L364-L372
    1133             :          - Fallback to SHT_DYNAMIC if PT missing/invalid: https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L374-L387
    1134             :        If neither exists, return OK (static file). If SHT_DYNAMIC exists but is invalid, error. */
    1135             : 
    1136       11116 :     ulong dynamic_table_start = ULONG_MAX;
    1137       11116 :     ulong dynamic_table_end = ULONG_MAX;
    1138             : 
    1139             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L364-L372 */
    1140       11116 :     if( info->phndx_dyn >= 0 ) {
    1141        9450 :       fd_elf64_phdr dyn_ph = FD_LOAD( fd_elf64_phdr, bin + phdr_start + (ulong)info->phndx_dyn*sizeof(fd_elf64_phdr) );
    1142        9450 :       dynamic_table_start = dyn_ph.p_offset;
    1143        9450 :       dynamic_table_end = dyn_ph.p_offset + dyn_ph.p_filesz;
    1144             : 
    1145             :       /* slice_from_program_header also checks that the size of the
    1146             :          slice is a multiple of the type size and that the alignment is
    1147             :          correct. */
    1148        9450 :       if( FD_UNLIKELY( dynamic_table_end<dynamic_table_start ||
    1149        9450 :                        dynamic_table_end>bin_sz ||
    1150        9450 :                        dyn_ph.p_filesz%sizeof(fd_elf64_dyn)!=0UL ||
    1151        9450 :                        !fd_ulong_is_aligned( dynamic_table_start, 8UL ) ) ) {
    1152             :         /* skip - try SHT_DYNAMIC instead */
    1153          72 :         dynamic_table_start = ULONG_MAX;
    1154          72 :         dynamic_table_end = ULONG_MAX;
    1155          72 :       }
    1156        9450 :     }
    1157             : 
    1158             :     /* If PT_DYNAMIC did not validate, try SHT_DYNAMIC
    1159             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L376-L387 */
    1160       11116 :     if( dynamic_table_start==ULONG_MAX && info->shndx_dyn >= 0 ) {
    1161        1594 :       fd_elf64_shdr dyn_sh = FD_LOAD( fd_elf64_shdr, bin + shdr_start + (ulong)info->shndx_dyn*sizeof(fd_elf64_shdr) );
    1162        1594 :       dynamic_table_start = dyn_sh.sh_offset;
    1163        1594 :       if( FD_UNLIKELY( ( __builtin_uaddl_overflow( dyn_sh.sh_offset, dyn_sh.sh_size, &dynamic_table_end ) ) || /* checked_add */
    1164        1594 :                        ( dyn_sh.sh_size % sizeof(fd_elf64_dyn) != 0UL ) || /* slice_from_bytes InvalidSize */
    1165        1594 :                        ( dynamic_table_end > bin_sz )                   || /* slice_from_bytes OutOfBounds */
    1166        1594 :                        !fd_ulong_is_aligned( dynamic_table_start, 8UL )    /* slice_from_bytes InvalidAlignment */ ) ) {
    1167             :         /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L382-L385 */
    1168           2 :         return FD_SBPF_ELF_PARSER_ERR_INVALID_DYNAMIC_SECTION_TABLE;
    1169           2 :       }
    1170        1594 :     }
    1171             : 
    1172             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L393 */
    1173       11114 :     if( dynamic_table_start==ULONG_MAX ) {
    1174          38 :       return FD_SBPF_ELF_SUCCESS;
    1175          38 :     }
    1176             : 
    1177             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L396-L407 */
    1178       11076 :     ulong dynamic_table[ FD_ELF_DT_NUM ] = { 0UL };
    1179       11076 :     ulong dyn_cnt = (dynamic_table_end - dynamic_table_start) / (ulong)sizeof(fd_elf64_dyn);
    1180      120734 :     for( ulong i = 0UL; i<dyn_cnt; i++ ) {
    1181      119053 :       fd_elf64_dyn dyn = FD_LOAD( fd_elf64_dyn, bin + dynamic_table_start + i*sizeof(fd_elf64_dyn) );
    1182             : 
    1183      119053 :       if( FD_UNLIKELY( dyn.d_tag==FD_ELF_DT_NULL ) ) {
    1184        9395 :         break;
    1185        9395 :       }
    1186      109658 :       if( FD_UNLIKELY( dyn.d_tag>=FD_ELF_DT_NUM ) ) {
    1187       15248 :         continue;
    1188       15248 :       }
    1189             : 
    1190       94410 :       dynamic_table[ dyn.d_tag ] = dyn.d_un.d_val;
    1191       94410 :     }
    1192             : 
    1193             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L409
    1194             :        solana_sbpf::elf_parser::Elf64::parse_dynamic_relocations */
    1195       11076 :     do {
    1196       11076 :       ulong vaddr = dynamic_table[ FD_ELF_DT_REL ];
    1197       11076 :       if( FD_UNLIKELY( vaddr==0UL ) ) {
    1198         110 :         break; /* from this do-while */
    1199         110 :       }
    1200             : 
    1201       10966 :       if ( FD_UNLIKELY( dynamic_table[ FD_ELF_DT_RELENT ] != sizeof(fd_elf64_rel) ) ) {
    1202           1 :         return FD_SBPF_ELF_PARSER_ERR_INVALID_DYNAMIC_SECTION_TABLE;
    1203           1 :       }
    1204             : 
    1205       10965 :       ulong size = dynamic_table[ FD_ELF_DT_RELSZ ];
    1206       10965 :       if( FD_UNLIKELY( size==0UL ) ) {
    1207           7 :         return FD_SBPF_ELF_PARSER_ERR_INVALID_DYNAMIC_SECTION_TABLE;
    1208           7 :       }
    1209             : 
    1210             :       /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L430-L444 */
    1211       10958 :       _Bool         offset_found = 0;
    1212       10958 :       ulong         offset;
    1213       10958 :       fd_elf64_phdr phdr;
    1214       28859 :       for( ulong i=0; i<ehdr.e_phnum; i++ ) {  /* program_header_for_vaddr */
    1215       27199 :         phdr = FD_LOAD( fd_elf64_phdr, bin + phdr_start + i*sizeof(fd_elf64_phdr) );
    1216       27199 :         ulong p_vaddr0 = phdr.p_vaddr;
    1217       27199 :         ulong p_memsz  = phdr.p_memsz;
    1218       27199 :         ulong p_vaddr1;
    1219       27199 :         if( FD_UNLIKELY( __builtin_uaddl_overflow( p_vaddr0, p_memsz, &p_vaddr1 ) ) ) {
    1220           1 :           return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
    1221           1 :         }
    1222       27198 :         if( p_vaddr0 <= vaddr && vaddr < p_vaddr1 ) {
    1223        9297 :           offset_found = 1;
    1224        9297 :           break;
    1225        9297 :         }
    1226       27198 :       }
    1227       10957 :       if( offset_found ) {
    1228        9289 :         if( FD_UNLIKELY( __builtin_usubl_overflow( vaddr, phdr.p_vaddr, &offset ) ) ) {
    1229           0 :           return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
    1230           0 :         }
    1231        9289 :         if( FD_UNLIKELY( __builtin_uaddl_overflow( offset, phdr.p_offset, &offset ) ) ) {
    1232           0 :           return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
    1233           0 :         }
    1234        9289 :       } else {
    1235        4764 :         for( ulong i=0; i<ehdr.e_shnum; i++ ) {  /* section_header_table.iter().find(...) */
    1236        4620 :           fd_elf64_shdr shdr = FD_LOAD( fd_elf64_shdr, bin + shdr_start + i*sizeof(fd_elf64_shdr) );
    1237        4620 :           if( shdr.sh_addr == vaddr ) {
    1238        1524 :             offset       = shdr.sh_offset;
    1239        1524 :             offset_found = 1;
    1240        1524 :             break;
    1241        1524 :           }
    1242        4620 :         }
    1243        1668 :         if( FD_UNLIKELY( !offset_found ) ) {
    1244           1 :           return FD_SBPF_ELF_PARSER_ERR_INVALID_DYNAMIC_SECTION_TABLE;
    1245           1 :         }
    1246        1668 :       }
    1247             :       /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L446-L448 */
    1248       10956 :       ulong offset_plus_size;
    1249       10956 :       if( FD_UNLIKELY( __builtin_uaddl_overflow( offset, size, &offset_plus_size ) ) ) {
    1250           1 :         return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
    1251           1 :       }
    1252             : 
    1253             :       /* slice_from_bytes checks that size is a multiple of the type
    1254             :          size and that the alignment of the bytes + offset is correct. */
    1255       10955 :       if( FD_UNLIKELY( ( size%sizeof(fd_elf64_rel)!=0UL ) ||
    1256       10955 :                        ( offset_plus_size>bin_sz ) ||
    1257       10955 :                        ( !fd_ulong_is_aligned( offset, 8UL ) ) ) ) {
    1258           4 :         return FD_SBPF_ELF_PARSER_ERR_INVALID_DYNAMIC_SECTION_TABLE;
    1259           4 :       }
    1260             : 
    1261             :       /* Save the dynamic relocation table info */
    1262       10951 :       info->dt_rel_off = (uint)offset;
    1263       10951 :       info->dt_rel_sz  = (uint)size;
    1264       10951 :     } while( 0 ); /* so we can break out */
    1265             : 
    1266             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L410 */
    1267       11061 :     do {
    1268             :       /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L452-L455 */
    1269       11061 :       ulong vaddr = dynamic_table[ FD_ELF_DT_SYMTAB ];
    1270       11061 :       if( FD_UNLIKELY( vaddr==0UL ) ) {
    1271          55 :         break; /* from this do-while */
    1272          55 :       }
    1273             : 
    1274       11006 :       fd_elf64_shdr shdr_sym = { 0 };
    1275       61134 :       for( ulong i=0; i<ehdr.e_shnum; i++ ) {
    1276             :         /* Again... */
    1277       60991 :         shdr_sym = FD_LOAD( fd_elf64_shdr, bin + shdr_start + i*sizeof(fd_elf64_shdr) );
    1278       60991 :         if( shdr_sym.sh_addr == vaddr ) {
    1279       10863 :           info->shndx_dynsymtab = (int)i;
    1280       10863 :           break;
    1281       10863 :         }
    1282       60991 :       }
    1283             : 
    1284             :       /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L457-L461 */
    1285       11006 :       if( FD_UNLIKELY( info->shndx_dynsymtab==-1 ) ) {
    1286           1 :         return FD_SBPF_ELF_PARSER_ERR_INVALID_DYNAMIC_SECTION_TABLE;
    1287           1 :       }
    1288             : 
    1289             :       /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L463-L464 */
    1290       11005 :       {
    1291       11005 :         if( FD_UNLIKELY( shdr_sym.sh_type != FD_ELF_SHT_SYMTAB && shdr_sym.sh_type != FD_ELF_SHT_DYNSYM ) ) {
    1292           1 :           return FD_SBPF_ELF_PARSER_ERR_INVALID_SECTION_HEADER;
    1293           1 :         }
    1294       11004 :         ulong shdr_sym_start = shdr_sym.sh_offset;
    1295       11004 :         ulong shdr_sym_end;
    1296             :         /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L574
    1297             :            https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf_parser/mod.rs#L671 */
    1298       11004 :         if( FD_UNLIKELY( __builtin_uaddl_overflow( shdr_sym.sh_offset, shdr_sym.sh_size, &shdr_sym_end ) ) ) {
    1299           0 :           return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
    1300           0 :         }
    1301             :         /* slice_from_bytes InvalidSize */
    1302       11004 :         if( FD_UNLIKELY( shdr_sym.sh_size%sizeof(fd_elf64_sym) ) ) {
    1303           1 :           return FD_SBPF_ELF_PARSER_ERR_INVALID_SIZE;
    1304           1 :         }
    1305             :         /* slice_from_bytes OutOfBounds */
    1306       11003 :         if( FD_UNLIKELY( shdr_sym_end>bin_sz ) ) {
    1307           0 :           return FD_SBPF_ELF_PARSER_ERR_OUT_OF_BOUNDS;
    1308           0 :         }
    1309             :         /* slice_from_bytes InvalidAlignment */
    1310       11003 :         if( FD_UNLIKELY( !fd_ulong_is_aligned( shdr_sym_start, 8UL ) ) ) {
    1311           2 :           return FD_SBPF_ELF_PARSER_ERR_INVALID_ALIGNMENT;
    1312           2 :         }
    1313       11003 :       }
    1314       11003 :     } while( 0 ); /* so we can break out */
    1315       11061 :   }
    1316             : 
    1317       11056 :   return FD_SBPF_ELF_SUCCESS;
    1318       11061 : }
    1319             : 
    1320             : /* Performs validation checks on the ELF. Returns an ElfError on failure
    1321             :    and 0 on success.
    1322             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L719-L809 */
    1323             : static int
    1324             : fd_sbpf_lenient_elf_validate( fd_sbpf_elf_info_t * info,
    1325             :                               void const *         bin,
    1326             :                               ulong                bin_sz,
    1327       10941 :                               fd_elf64_shdr *      text_shdr ) {
    1328             : 
    1329             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L721-L736 */
    1330       10941 :   fd_elf64_ehdr ehdr = FD_LOAD( fd_elf64_ehdr, bin );
    1331       10941 :   if( FD_UNLIKELY( ehdr.e_ident[ FD_ELF_EI_CLASS ] != FD_ELF_CLASS_64 ) ) {
    1332           0 :     return FD_SBPF_ELF_ERR_WRONG_CLASS;
    1333           0 :   }
    1334       10941 :   if( FD_UNLIKELY( ehdr.e_ident[ FD_ELF_EI_DATA  ] != FD_ELF_DATA_LE ) ) {
    1335           0 :     return FD_SBPF_ELF_ERR_WRONG_ENDIANNESS;
    1336           0 :   }
    1337       10941 :   if( FD_UNLIKELY( ehdr.e_ident[ FD_ELF_EI_OSABI ] != FD_ELF_OSABI_NONE ) ) {
    1338           1 :     return FD_SBPF_ELF_ERR_WRONG_ABI;
    1339           1 :   }
    1340       10940 :   if( FD_UNLIKELY( ehdr.e_machine != FD_ELF_EM_BPF && ehdr.e_machine != FD_ELF_EM_SBPF ) ) {
    1341           1 :     return FD_SBPF_ELF_ERR_WRONG_MACHINE;
    1342           1 :   }
    1343       10939 :   if( FD_UNLIKELY( ehdr.e_type != FD_ELF_ET_DYN ) ) {
    1344           1 :     return FD_SBPF_ELF_ERR_WRONG_TYPE;
    1345           1 :   }
    1346             : 
    1347             :   /* This code doesn't do anything:
    1348             :      1. version is already checked at the very beginning of elf_peek
    1349             :      2. the if condition is never true because sbpf_version is always v0
    1350             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L738-L763 */
    1351             : 
    1352       10938 :   ulong shdr_start = ehdr.e_shoff;
    1353       10938 :   ulong section_names_shdr_idx = ehdr.e_shstrndx;
    1354       10938 :   fd_elf64_shdr section_names_shdr = FD_LOAD( fd_elf64_shdr, bin + shdr_start + section_names_shdr_idx*sizeof(fd_elf64_shdr) );
    1355             : 
    1356             :   /* We do a single iteration over the section header table, collect all info
    1357             :      we need and return the errors later to match Agave. */
    1358             : 
    1359       10938 :   int shndx_text    = -1;
    1360       10938 :   int writeable_err = 0;
    1361       10938 :   int oob_err       = 0;
    1362      107160 :   for( ulong i=0UL; i<ehdr.e_shnum; i++ ) {
    1363             :     /* Again... */
    1364       96224 :     fd_elf64_shdr shdr = FD_LOAD( fd_elf64_shdr, bin + ehdr.e_shoff + i*sizeof(fd_elf64_shdr) );
    1365             : 
    1366       96224 :     uchar const * name;
    1367       96224 :     ulong         name_len;
    1368       96224 :     int res = fd_sbpf_lenient_get_string_in_section( bin, bin_sz, &section_names_shdr, shdr.sh_name, FD_SBPF_SECTION_NAME_SZ_MAX, &name, &name_len );
    1369       96224 :     if( FD_UNLIKELY( res ) ) {
    1370             :       /* this can never fail because it was checked above, but safer to keep it */
    1371           0 :       return fd_sbpf_elf_parser_err_to_elf_err( res );
    1372           0 :     }
    1373             : 
    1374             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L765-L775 */
    1375       96224 :     if( FD_UNLIKELY( fd_sbpf_slice_cstr_eq( name, name_len, ".text" ) ) ) {
    1376       10943 :       if( FD_LIKELY( shndx_text==-1 ) ) {
    1377       10941 :         *text_shdr = shdr;  /* Store the text section header */
    1378       10941 :         shndx_text = (int)i;
    1379       10941 :       } else {
    1380           2 :         return FD_SBPF_ELF_ERR_NOT_ONE_TEXT_SECTION;
    1381           2 :       }
    1382       10943 :     }
    1383             : 
    1384             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L780-L791 */
    1385       96222 :     if( FD_UNLIKELY( fd_sbpf_slice_cstr_start_with( name, name_len, ".bss" ) ||
    1386       96222 :                      ( ( ( shdr.sh_flags & (FD_ELF_SHF_ALLOC | FD_ELF_SHF_WRITE) ) == (FD_ELF_SHF_ALLOC | FD_ELF_SHF_WRITE) ) &&
    1387       96222 :                            fd_sbpf_slice_cstr_start_with( name, name_len, ".data" ) &&
    1388       96222 :                            !fd_sbpf_slice_cstr_start_with( name, name_len, ".data.rel" ) ) ) ) {
    1389             :       /* to match Agave return error we can't fail here */
    1390           7 :       writeable_err = 1;
    1391           7 :     }
    1392             : 
    1393             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L793-L802 */
    1394       96222 :     ulong shdr_end;
    1395       96222 :     if( FD_UNLIKELY( __builtin_uaddl_overflow( shdr.sh_offset, shdr.sh_size, &shdr_end ) ||
    1396       96222 :                      shdr_end>bin_sz ) ) {
    1397           1 :       oob_err = 1;
    1398           1 :     }
    1399       96222 :   }
    1400             : 
    1401             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L776-L778 */
    1402       10936 :   if( FD_UNLIKELY( shndx_text==-1 ) ) {
    1403          27 :     return FD_SBPF_ELF_ERR_NOT_ONE_TEXT_SECTION;
    1404          27 :   }
    1405             : 
    1406             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L786-L788 */
    1407       10909 :   if( FD_UNLIKELY( writeable_err ) ) {
    1408           6 :     return FD_SBPF_ELF_ERR_WRITABLE_SECTION_NOT_SUPPORTED;
    1409           6 :   }
    1410             : 
    1411             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L798 */
    1412       10903 :   if( FD_UNLIKELY( oob_err ) ) {
    1413           1 :     return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1414           1 :   }
    1415             : 
    1416             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L804-L806 */
    1417       10902 :   if( FD_UNLIKELY( !(
    1418       10902 :     text_shdr->sh_addr <= ehdr.e_entry && ehdr.e_entry < fd_ulong_sat_add( text_shdr->sh_addr, text_shdr->sh_size )
    1419       10902 :   ) ) ) {
    1420           4 :     return FD_SBPF_ELF_ERR_ENTRYPOINT_OUT_OF_BOUNDS;
    1421           4 :   }
    1422             : 
    1423             :   /* Get text section file ranges to calculate the size. */
    1424       10898 :   fd_sbpf_range_t text_section_range;
    1425       10898 :   fd_shdr_get_file_range( text_shdr, &text_section_range );
    1426             : 
    1427       10898 :   info->text_off      = (uint)text_shdr->sh_addr;
    1428       10898 :   info->text_sz       = text_section_range.hi-text_section_range.lo;
    1429       10898 :   info->text_cnt      = (uint)( info->text_sz/8UL );
    1430       10898 :   info->shndx_text    = shndx_text;
    1431       10898 :   info->calldests_max = fd_ulong_min( text_shdr->sh_size, bin_sz )/8UL;
    1432             : 
    1433       10898 :   return FD_SBPF_ELF_SUCCESS;
    1434       10902 : }
    1435             : 
    1436             : /* First part of Agave's load_with_lenient_parser(). We split up this
    1437             :    function into two parts so we know how much memory we need to
    1438             :    allocate for the loading step. Returns an ElfError on failure and 0
    1439             :    on success.
    1440             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L593-L638 */
    1441             : static int
    1442             : fd_sbpf_elf_peek_lenient( fd_sbpf_elf_info_t *            info,
    1443             :                           void const *                    bin,
    1444             :                           ulong                           bin_sz,
    1445       13460 :                           fd_sbpf_loader_config_t const * config ) {
    1446             : 
    1447             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L607 */
    1448       13460 :   int res = fd_sbpf_lenient_elf_parse( info, bin, bin_sz );
    1449       13460 :   if( FD_UNLIKELY( res<0 ) ) {
    1450        2363 :     return fd_sbpf_elf_parser_err_to_elf_err( res );
    1451        2363 :   }
    1452             : 
    1453             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L617 */
    1454       11097 :   fd_elf64_shdr text_shdr = { 0 };
    1455       11097 :   res = fd_sbpf_lenient_elf_validate( info, bin, bin_sz, &text_shdr );
    1456       11097 :   if( FD_UNLIKELY( res<0 ) ) {
    1457          43 :     return res;
    1458          43 :   }
    1459             : 
    1460             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L620-L638 */
    1461       11054 :   {
    1462       11054 :     ulong text_section_vaddr = fd_ulong_sat_add( text_shdr.sh_addr, FD_SBPF_MM_RODATA_ADDR );
    1463       11054 :     ulong vaddr_end          = text_section_vaddr;
    1464             : 
    1465             :     /* Validate bounds and text section addrs / offsets.
    1466             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L632-L638 */
    1467       11054 :     if( FD_UNLIKELY( ( config->reject_broken_elfs && text_shdr.sh_addr!=text_shdr.sh_offset ) ||
    1468       11054 :                        vaddr_end>FD_SBPF_MM_STACK_ADDR ) ) {
    1469           1 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1470           1 :     }
    1471       11054 :   }
    1472             : 
    1473             :   /* Peek (vs load) stops here
    1474             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L638 */
    1475             : 
    1476       11053 :   return FD_SBPF_ELF_SUCCESS;
    1477       11054 : }
    1478             : 
    1479             : static int
    1480             : fd_sbpf_program_get_sbpf_version_or_err( void const *                    bin,
    1481             :                                          ulong                           bin_sz,
    1482       30746 :                                          fd_sbpf_loader_config_t const * config ) {
    1483             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L376-L381 */
    1484       30746 :   const ulong E_FLAGS_OFFSET = 48UL;
    1485             : 
    1486       30746 :   if( FD_UNLIKELY( bin_sz<E_FLAGS_OFFSET+sizeof(uint) ) ) {
    1487       15318 :     return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1488       15318 :   }
    1489       15428 :   uint e_flags = FD_LOAD( uint, bin+E_FLAGS_OFFSET );
    1490             : 
    1491             :   /* https://github.com/anza-xyz/sbpf/blob/v0.13.0/src/elf.rs#L382-L390 */
    1492       15428 :   uint sbpf_version = ( e_flags < FD_SBPF_VERSION_COUNT ) ? e_flags : FD_SBPF_RESERVED;
    1493             : 
    1494             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L399-L401 */
    1495       15428 :   if( FD_UNLIKELY( !( config->sbpf_min_version <= sbpf_version && sbpf_version <= config->sbpf_max_version ) ) ) {
    1496        1956 :     return FD_SBPF_ELF_ERR_UNSUPPORTED_SBPF_VERSION;
    1497        1956 :   }
    1498             : 
    1499             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L403-L407 */
    1500       13472 :   return (int)sbpf_version;
    1501       15428 : }
    1502             : 
    1503             : int
    1504             : fd_sbpf_elf_peek( fd_sbpf_elf_info_t *            info,
    1505             :                   void const *                    bin,
    1506             :                   ulong                           bin_sz,
    1507       30746 :                   fd_sbpf_loader_config_t const * config ) {
    1508             :   /* Extract sbpf_version (or error)
    1509             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L376-L401 */
    1510       30746 :   int maybe_sbpf_version = fd_sbpf_program_get_sbpf_version_or_err( bin, bin_sz, config );
    1511       30746 :   if( FD_UNLIKELY( maybe_sbpf_version<0 ) ) {
    1512       17274 :     return maybe_sbpf_version;
    1513       17274 :   }
    1514             : 
    1515             :   /* Initialize info struct */
    1516       13472 :   *info = (fd_sbpf_elf_info_t) {
    1517       13472 :     .bin_sz          = 0U,
    1518       13472 :     .text_off        = 0U,
    1519       13472 :     .text_cnt        = 0U,
    1520       13472 :     .text_sz         = 0UL,
    1521       13472 :     .shndx_text      = -1,
    1522       13472 :     .shndx_symtab    = -1,
    1523       13472 :     .shndx_strtab    = -1,
    1524       13472 :     .shndx_dyn       = -1,
    1525       13472 :     .shndx_dynstr    = -1,
    1526       13472 :     .shndx_dynsymtab = -1,
    1527       13472 :     .phndx_dyn       = -1,
    1528       13472 :     .dt_rel_off      = 0UL,
    1529       13472 :     .dt_rel_sz       = 0UL,
    1530       13472 :     .sbpf_version    = (uint)maybe_sbpf_version,
    1531             :     /* !!! Keep this in sync with -Werror=missing-field-initializers */
    1532       13472 :   };
    1533             : 
    1534             :   /* Invoke strict vs lenient parser. The strict parser is used for
    1535             :      SBPF version >= 3. The strict parser also returns an ElfParserError
    1536             :      while the lenient parser returns an ElfError, so we have to map
    1537             :      the strict parser's error code.
    1538             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L403-L407 */
    1539       13472 :   if( FD_UNLIKELY( fd_sbpf_enable_stricter_elf_headers_enabled( info->sbpf_version ) ) ) {
    1540           0 :     return fd_sbpf_elf_parser_err_to_elf_err( fd_sbpf_elf_peek_strict( info, bin, bin_sz ) );
    1541           0 :   }
    1542       13472 :   return fd_sbpf_elf_peek_lenient( info, bin, bin_sz, config );
    1543       13472 : }
    1544             : 
    1545             : /* Parses and concatenates the readonly data sections.  This function
    1546             :    also computes and sets the rodata_sz field inside the SBPF program
    1547             :    struct.  scratch is a pointer to a scratch area with size scratch_sz,
    1548             :    used to allocate a temporary buffer for the parsed rodata sections
    1549             :    before copying it back into the rodata (recommended size is bin_sz).
    1550             :    Returns 0 on success and an ElfError error code on failure.  On
    1551             :    success, the rodata and rodata_sz fields in the sbpf program struct
    1552             :    are updated.
    1553             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L812-L987 */
    1554             : static int
    1555             : fd_sbpf_parse_ro_sections( fd_sbpf_program_t *             prog,
    1556             :                            void const *                    bin,
    1557             :                            ulong                           bin_sz,
    1558             :                            fd_sbpf_loader_config_t const * config,
    1559             :                            void *                          scratch,
    1560       10873 :                            ulong                           scratch_sz ) {
    1561             : 
    1562       10873 :   fd_sbpf_elf_t const * elf                = (fd_sbpf_elf_t const *)bin;
    1563       10873 :   fd_elf64_shdr const * shdrs              = (fd_elf64_shdr const *)( elf->bin + elf->ehdr.e_shoff );
    1564       10873 :   fd_elf64_shdr const * section_names_shdr = &shdrs[ elf->ehdr.e_shstrndx ];
    1565       10873 :   uchar *               rodata             = prog->rodata;
    1566             : 
    1567             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L818-L834 */
    1568       10873 :   ulong lowest_addr          = ULONG_MAX; /* Lowest section address */
    1569       10873 :   ulong highest_addr         = 0UL;       /* Highest section address */
    1570       10873 :   ulong ro_fill_length       = 0UL;       /* Aggregated section length, excluding gaps between sections */
    1571       10873 :   uchar invalid_offsets      = 0;         /* Whether the section has invalid offsets */
    1572             : 
    1573             :   /* Store the section header indices of ro slices to fill later. */
    1574       10873 :   ulong ro_slices_shidxs[ elf->ehdr.e_shnum ];
    1575       10873 :   ulong ro_slices_cnt = 0UL;
    1576             : 
    1577             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L837-L909 */
    1578      106549 :   for( uint i=0U; i<elf->ehdr.e_shnum; i++ ) {
    1579       95682 :     fd_elf64_shdr const * section_header = &shdrs[ i ];
    1580             : 
    1581             :     /* Match the section name.
    1582             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L838-L845 */
    1583       95682 :     uchar const * name;
    1584       95682 :     ulong         name_len;
    1585       95682 :     if( FD_UNLIKELY( fd_sbpf_lenient_get_string_in_section( bin, bin_sz, section_names_shdr, section_header->sh_name, FD_SBPF_SECTION_NAME_SZ_MAX, &name, &name_len ) ) ) {
    1586           0 :       continue;
    1587           0 :     }
    1588             : 
    1589       95682 :     if( FD_UNLIKELY( !fd_sbpf_slice_cstr_eq( name, name_len, ".text" ) &&
    1590       95682 :                      !fd_sbpf_slice_cstr_eq( name, name_len, ".rodata" ) &&
    1591       95682 :                      !fd_sbpf_slice_cstr_eq( name, name_len, ".data.rel.ro" ) &&
    1592       95682 :                      !fd_sbpf_slice_cstr_eq( name, name_len, ".eh_frame" ) ) ) {
    1593       66320 :       continue;
    1594       66320 :     }
    1595             : 
    1596       29362 :     ulong section_addr = section_header->sh_addr;
    1597             : 
    1598             :     /* Handling for the section header offsets. If ELF vaddrs are
    1599             :        enabled, the section header addresses are allowed to be > the
    1600             :        section header offsets, as long as address - offset is constant
    1601             :        across all sections. Otherwise, the section header addresses
    1602             :        and offsets must match.
    1603             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L865-L884 */
    1604       29566 :     if( FD_LIKELY( !invalid_offsets ) ) {
    1605             :       /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L866-L880 */
    1606       29566 :       if( FD_UNLIKELY( section_addr!=section_header->sh_offset ) ) {
    1607          11 :         invalid_offsets = 1;
    1608          11 :       }
    1609       29566 :     }
    1610             : 
    1611             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L886-L897 */
    1612       29362 :     ulong vaddr_end = section_addr;
    1613       29563 :     if( section_addr<FD_SBPF_MM_RODATA_ADDR ) {
    1614       29563 :       vaddr_end = fd_ulong_sat_add( section_addr, FD_SBPF_MM_RODATA_ADDR );
    1615       29563 :     }
    1616             : 
    1617       29362 :     if( FD_UNLIKELY( ( config->reject_broken_elfs && invalid_offsets ) ||
    1618       29362 :                        vaddr_end>FD_SBPF_MM_STACK_ADDR ) ) {
    1619           6 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1620           6 :     }
    1621             : 
    1622             :     /* Append the ro slices vector and update the lowest / highest addr
    1623             :        and ro_fill_length variables. Agave stores three fields in the
    1624             :        ro slices array that can all be derived from the section header,
    1625             :        so we just need to store the indices.
    1626             : 
    1627             :        The call to fd_shdr_get_file_range() is allowed to fail (Agave's
    1628             :        unwrap_or_default() call returns a range of 0..0 in this case).
    1629             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L899-L908 */
    1630       29356 :     fd_sbpf_range_t section_header_range;
    1631       29356 :     fd_shdr_get_file_range( section_header, &section_header_range );
    1632       29356 :     if( FD_UNLIKELY( section_header_range.hi>bin_sz ) ) {
    1633           0 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1634           0 :     }
    1635       29356 :     ulong section_data_len = section_header_range.hi-section_header_range.lo;
    1636             : 
    1637       29356 :     lowest_addr    = fd_ulong_min( lowest_addr, section_addr );
    1638       29356 :     highest_addr   = fd_ulong_max( highest_addr, fd_ulong_sat_add( section_addr, section_data_len ) );
    1639       29356 :     ro_fill_length = fd_ulong_sat_add( ro_fill_length, section_data_len );
    1640       29356 :     ro_slices_shidxs[ ro_slices_cnt++ ] = i;
    1641       29356 :   }
    1642             : 
    1643             :   /* This checks that the ro sections are not overlapping. This check
    1644             :      is incomplete, however, because it does not account for the
    1645             :      existence of gaps between sections in calculations.
    1646             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L910-L913 */
    1647       10867 :   if( FD_UNLIKELY( config->reject_broken_elfs &&
    1648       10867 :                    fd_ulong_sat_add( lowest_addr, ro_fill_length )>highest_addr ) ) {
    1649           0 :     return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1650           0 :   }
    1651             : 
    1652             :   /* Note that optimize_rodata is always false.
    1653             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L923-L984 */
    1654       10867 :  {
    1655             :     /* Readonly / non-readonly sections are mixed, so non-readonly
    1656             :        sections must be zeroed and the readonly sections must be copied
    1657             :        at their respective offsets.
    1658             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L950-L983 */
    1659       10867 :     lowest_addr = 0UL;
    1660             : 
    1661             :     /* Bounds check. */
    1662       10867 :     ulong buf_len = highest_addr;
    1663       10867 :     if( FD_UNLIKELY( buf_len>bin_sz ) ) {
    1664           3 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1665           3 :     }
    1666             : 
    1667             :     /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L971-L976 */
    1668       10864 :     if( FD_UNLIKELY( buf_len>scratch_sz ) ) {
    1669           0 :       FD_LOG_CRIT(( "scratch_sz is too small: %lu, required: %lu", scratch_sz, buf_len ));
    1670           0 :     }
    1671       10864 :     uchar * ro_section = scratch;
    1672       10864 :     fd_memset( ro_section, 0, buf_len );
    1673             : 
    1674       40648 :     for( ulong i=0UL; i<ro_slices_cnt; i++ ) {
    1675       29784 :       ulong sh_idx                       = ro_slices_shidxs[ i ];
    1676       29784 :       fd_elf64_shdr const * shdr         = &shdrs[ sh_idx ];
    1677       29784 :       ulong                 section_addr = shdr->sh_addr;
    1678             : 
    1679             :       /* This was checked above and should never fail. */
    1680       29784 :       fd_sbpf_range_t slice_range;
    1681       29784 :       fd_shdr_get_file_range( shdr, &slice_range );
    1682       29784 :       if( FD_UNLIKELY( slice_range.hi>bin_sz ) ) {
    1683           0 :         return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1684           0 :       }
    1685             : 
    1686       29784 :       ulong buf_offset_start = fd_ulong_sat_sub( section_addr, lowest_addr );
    1687       29784 :       ulong slice_len        = slice_range.hi-slice_range.lo;
    1688       29784 :       if( FD_UNLIKELY( slice_len>buf_len ) ) {
    1689           0 :         return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1690           0 :       }
    1691             : 
    1692       29784 :       fd_memcpy( ro_section+buf_offset_start, rodata+slice_range.lo, slice_len );
    1693       29784 :     }
    1694             : 
    1695             :     /* Copy the rodata section back in. */
    1696       10864 :     prog->rodata_sz = buf_len;
    1697       10864 :     fd_memcpy( rodata, ro_section, buf_len );
    1698       10864 :   }
    1699             : 
    1700       10864 :   return FD_SBPF_ELF_SUCCESS;
    1701       10864 : }
    1702             : 
    1703             : /* Applies ELF relocations in-place. Returns 0 on success and an
    1704             :    ElfError error code on failure.
    1705             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L990-L1331 */
    1706             : static int
    1707             : fd_sbpf_program_relocate( fd_sbpf_program_t *             prog,
    1708             :                           void const *                    bin,
    1709             :                           ulong                           bin_sz,
    1710             :                           fd_sbpf_loader_config_t const * config,
    1711       11060 :                           fd_sbpf_loader_t *              loader ) {
    1712       11060 :   fd_sbpf_elf_info_t const * elf_info = &prog->info;
    1713       11060 :   fd_sbpf_elf_t const *      elf      = (fd_sbpf_elf_t const *)bin;
    1714       11060 :   uchar *                    rodata   = prog->rodata;
    1715       11060 :   fd_elf64_shdr const *      shdrs    = (fd_elf64_shdr const *)( elf->bin + elf->ehdr.e_shoff );
    1716       11060 :   fd_elf64_shdr const *      shtext   = &shdrs[ elf_info->shndx_text ];
    1717             : 
    1718             :   /* Copy rodata segment */
    1719       11060 :   fd_memcpy( rodata, elf->bin, elf_info->bin_sz );
    1720             : 
    1721             :   /* Fixup all program counter relative call instructions
    1722             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1005-L1041 */
    1723       11060 :   {
    1724             :     /* Validate the bytes range of the text section.
    1725             :        https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1006-L1008 */
    1726       11060 :     fd_sbpf_range_t text_section_range;
    1727       11060 :     fd_shdr_get_file_range( shtext, &text_section_range );
    1728             : 
    1729       11060 :     ulong insn_cnt = (text_section_range.hi-text_section_range.lo)/8UL;
    1730       11060 :     if( FD_UNLIKELY( shtext->sh_size+shtext->sh_offset>bin_sz ) ) {
    1731           0 :       return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1732           0 :     }
    1733             : 
    1734       11060 :     uchar * ptr = rodata + shtext->sh_offset;
    1735             : 
    1736    83447318 :     for( ulong i=0UL; i<insn_cnt; i++, ptr+=8UL ) {
    1737    83436344 :       ulong insn = FD_LOAD( ulong, ptr );
    1738             : 
    1739             :       /* Check for call instruction.  If immediate is UINT_MAX, assume
    1740             :          that compiler generated a relocation instead.
    1741             :          https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1015 */
    1742    83436344 :       ulong opc  = insn & 0xFF;
    1743    83436344 :       int   imm  = (int)(insn >> 32UL);
    1744    83436344 :       if( (opc!=FD_SBPF_OP_CALL_IMM) || (imm==-1) ) continue;
    1745             : 
    1746             :       /* Calculate and check the target PC
    1747             :          https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1016-L1021 */
    1748     2086168 :       long target_pc = fd_long_sat_add( fd_long_sat_add( (long)i, 1L ), imm);
    1749     2086168 :       if( FD_UNLIKELY( target_pc<0L || target_pc>=(long)insn_cnt ) ) {
    1750          86 :         return FD_SBPF_ELF_ERR_RELATIVE_JUMP_OUT_OF_BOUNDS;
    1751          86 :       }
    1752             : 
    1753             :       /* Update the calldests
    1754             :          https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1027-L1032 */
    1755     2086082 :       uint pc_hash;
    1756     2086082 :       int err = fd_sbpf_register_function_hashed_legacy( loader, prog, NULL, 0UL, (ulong)target_pc, &pc_hash );
    1757     2086082 :       if( FD_UNLIKELY( err!=FD_SBPF_ELF_SUCCESS ) ) {
    1758           0 :         return err;
    1759           0 :       }
    1760             : 
    1761             :       /* Store PC hash in text section. Check for writes outside the
    1762             :          text section.
    1763             :          https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1034-L1038 */
    1764     2086082 :       ulong offset = fd_ulong_sat_add( fd_ulong_sat_mul( i, 8UL ), 4UL ); // offset in text section
    1765     2086082 :       if( FD_UNLIKELY( offset+4UL>shtext->sh_size ) ) {
    1766           0 :         return FD_SBPF_ELF_ERR_VALUE_OUT_OF_BOUNDS;
    1767           0 :       }
    1768             : 
    1769     2086082 :       FD_STORE( uint, ptr+4UL, pc_hash );
    1770     2086082 :     }
    1771       11060 :   }
    1772             : 
    1773             :   /* Fixup all the relocations in the relocation section if exists. The
    1774             :      dynamic relocations table was already parsed and validated in
    1775             :      fd_sbpf_lenient_elf_parse().
    1776             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1046-L1304 */
    1777       10974 :   {
    1778       10974 :     fd_elf64_rel const *  dt_rels    = (fd_elf64_rel const *)( elf->bin + elf_info->dt_rel_off );
    1779       10974 :     uint                  dt_rel_cnt = elf_info->dt_rel_sz / sizeof(fd_elf64_rel);
    1780             : 
    1781     3586499 :     for( uint i=0U; i<dt_rel_cnt; i++ ) {
    1782     3576059 :       fd_elf64_rel const * dt_rel   = &dt_rels[ i ];
    1783     3576059 :       ulong                r_offset = dt_rel->r_offset;
    1784             : 
    1785             :       /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L1068-L1303 */
    1786     3576059 :       int err;
    1787     3576059 :       switch( FD_ELF64_R_TYPE( dt_rel->r_info ) ) {
    1788         206 :         case FD_ELF_R_BPF_64_64:
    1789         206 :           err = fd_sbpf_r_bpf_64_64( elf, bin_sz, rodata, elf_info, dt_rel, r_offset );
    1790         206 :           break;
    1791     3214221 :         case FD_ELF_R_BPF_64_RELATIVE:
    1792     3214221 :           err = fd_sbpf_r_bpf_64_relative(elf, bin_sz, rodata, elf_info, r_offset );
    1793     3214221 :           break;
    1794      603283 :         case FD_ELF_R_BPF_64_32:
    1795      603283 :           err = fd_sbpf_r_bpf_64_32( loader, prog, elf, bin_sz, rodata, elf_info, dt_rel, r_offset, config );
    1796      603283 :           break;
    1797          15 :         default:
    1798          15 :           return FD_SBPF_ELF_ERR_UNKNOWN_RELOCATION;
    1799     3576059 :       }
    1800             : 
    1801     3575578 :       if( FD_UNLIKELY( err!=FD_SBPF_ELF_SUCCESS ) ) {
    1802          53 :         return err;
    1803          53 :       }
    1804     3575578 :     }
    1805       10974 :   }
    1806             : 
    1807             :   /* ...rest of this function is a no-op because
    1808             :      enable_symbol_and_section_labels is disabled in production. */
    1809             : 
    1810       10440 :   return FD_SBPF_ELF_SUCCESS;
    1811       10974 : }
    1812             : 
    1813             : /* Second part of load_with_lenient_parser().
    1814             : 
    1815             :    This function is responsible for "loading" an sBPF program. This
    1816             :    means...
    1817             :    1. Applies any relocations in-place to the rodata section.
    1818             :    2. Registers the program entrypoint and other valid calldests.
    1819             :    3. Parses and validates the rodata sections, zeroing out any gaps
    1820             :       between sections.
    1821             : 
    1822             :    Returns 0 on success and an ElfError error code on failure.
    1823             : 
    1824             :    https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L640-L689
    1825             :  */
    1826             : static int
    1827             : fd_sbpf_program_load_lenient( fd_sbpf_program_t *             prog,
    1828             :                               void const *                    bin,
    1829             :                               ulong                           bin_sz,
    1830             :                               fd_sbpf_loader_t *              loader,
    1831             :                               fd_sbpf_loader_config_t const * config,
    1832             :                               void *                          scratch,
    1833       11061 :                               ulong                           scratch_sz ) {
    1834             : 
    1835             :   /* Load (vs peek) starts here
    1836             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L641 */
    1837             : 
    1838       11061 :   fd_sbpf_elf_t const * elf      = (fd_sbpf_elf_t const *)bin;
    1839       11061 :   fd_sbpf_elf_info_t *  elf_info = &prog->info;
    1840       11061 :   fd_elf64_shdr const * shdrs    = (fd_elf64_shdr const *)( elf->bin + elf->ehdr.e_shoff );
    1841       11061 :   fd_elf64_shdr const * sh_text  = &shdrs[ elf_info->shndx_text ];
    1842             : 
    1843             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L642-L647 */
    1844       11061 :   int err = fd_sbpf_program_relocate( prog, bin, bin_sz, config, loader );
    1845       11061 :   if( FD_UNLIKELY( err ) ) return err;
    1846             : 
    1847             :   /* https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L649-L653 */
    1848       10907 :   ulong offset = fd_ulong_sat_sub( elf->ehdr.e_entry, sh_text->sh_addr );
    1849       10907 :   if( FD_UNLIKELY( offset&0x7UL ) ) { /* offset % 8 != 0 */
    1850           1 :     return FD_SBPF_ELF_ERR_INVALID_ENTRYPOINT;
    1851           1 :   }
    1852             : 
    1853             :   /* Unregister the entrypoint from the calldests, and register the
    1854             :      entry_pc. Our behavior slightly diverges from Agave's because we
    1855             :      rely on an explicit entry_pc field within the elf_info struct
    1856             :      to handle the b"entrypoint" symbol, and rely on PC hash inverses
    1857             :      for any other CALL_IMM targets.
    1858             : 
    1859             :      Note that even though we won't use the calldests value for the
    1860             :      entry pc, we still need to "register" it to check for any potential
    1861             :      symbol collisions and report errors accordingly. We unregister it
    1862             :      first by setting it to ULONG_MAX.
    1863             : 
    1864             :      TODO: Add special casing for static syscalls enabled. For now, it
    1865             :      is not implemented.
    1866             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L654-L667 */
    1867       10906 :   prog->entry_pc = ULONG_MAX;
    1868       10906 :   ulong entry_pc = offset/8UL;
    1869       10906 :   err = fd_sbpf_register_function_hashed_legacy(
    1870       10906 :       loader,
    1871       10906 :       prog,
    1872       10906 :       (uchar const *)"entrypoint",
    1873       10906 :       strlen( "entrypoint" ),
    1874       10906 :       entry_pc,
    1875       10906 :       NULL );
    1876       10906 :   if( FD_UNLIKELY( err!=FD_SBPF_ELF_SUCCESS ) ) {
    1877           0 :     return err;
    1878           0 :   }
    1879             : 
    1880             :   /* Parse the ro sections.
    1881             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L669-L676 */
    1882       10906 :   err = fd_sbpf_parse_ro_sections( prog, bin, bin_sz, config, scratch, scratch_sz );
    1883       10906 :   if( FD_UNLIKELY( err!=FD_SBPF_ELF_SUCCESS ) ) {
    1884           9 :     return err;
    1885           9 :   }
    1886             : 
    1887       10897 :   return FD_SBPF_ELF_SUCCESS;
    1888       10906 : }
    1889             : 
    1890             : int
    1891             : fd_sbpf_program_load( fd_sbpf_program_t *             prog,
    1892             :                       void const *                    bin,
    1893             :                       ulong                           bin_sz,
    1894             :                       fd_sbpf_syscalls_t *            syscalls,
    1895             :                       fd_sbpf_loader_config_t const * config,
    1896             :                       void *                          scratch,
    1897       11061 :                       ulong                           scratch_sz ) {
    1898       11061 :   fd_sbpf_loader_t loader = {
    1899       11061 :     .calldests = prog->calldests,
    1900       11061 :     .syscalls  = syscalls,
    1901       11061 :   };
    1902             : 
    1903             :   /* Invoke strict vs lenient loader
    1904             :      Note: info.sbpf_version is already set by fd_sbpf_program_parse()
    1905             :      https://github.com/anza-xyz/sbpf/blob/v0.12.2/src/elf.rs#L403-L409 */
    1906       11061 :   if( FD_UNLIKELY( fd_sbpf_enable_stricter_elf_headers_enabled( prog->info.sbpf_version ) ) ) {
    1907             :     /* There is nothing else to do in the strict case except updating
    1908             :        the prog->rodata_sz field from phdr[ 1 ].p_memsz, and setting
    1909             :        the entry_pc. */
    1910           0 :     fd_elf64_ehdr ehdr     = FD_LOAD( fd_elf64_ehdr, bin );
    1911           0 :     fd_elf64_phdr phdr_0   = FD_LOAD( fd_elf64_phdr, bin+sizeof(fd_elf64_ehdr) );
    1912           0 :     fd_elf64_phdr phdr_1   = FD_LOAD( fd_elf64_phdr, bin+sizeof(fd_elf64_ehdr)+sizeof(fd_elf64_phdr) );
    1913           0 :     prog->rodata_sz        = phdr_1.p_memsz;
    1914           0 :     prog->entry_pc         = ( ehdr.e_entry-phdr_0.p_vaddr )/8UL;
    1915           0 :     return FD_SBPF_ELF_SUCCESS;
    1916           0 :   }
    1917       11061 :   int res = fd_sbpf_program_load_lenient( prog, bin, bin_sz, &loader, config, scratch, scratch_sz );
    1918       11061 :   if( FD_UNLIKELY( res!=FD_SBPF_ELF_SUCCESS ) ) {
    1919         164 :     return res;
    1920         164 :   }
    1921             : 
    1922       10897 :   return FD_SBPF_ELF_SUCCESS;
    1923       11061 : }
    1924             : 
    1925             : #undef ERR
    1926             : #undef FAIL
    1927             : #undef REQUIRE

Generated by: LCOV version 1.14