Vystem 0.2
This commit is contained in:
6
vybuild/_vyx_start.c
Normal file
6
vybuild/_vyx_start.c
Normal file
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
extern int main(void);
|
||||
void _vyx_start(void) {
|
||||
main();
|
||||
for (;;);
|
||||
}
|
||||
80
vybuild/api.h
Normal file
80
vybuild/api.h
Normal file
@@ -0,0 +1,80 @@
|
||||
#ifndef SPX_API_H
|
||||
#define SPX_API_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "params.h"
|
||||
|
||||
#define CRYPTO_ALGNAME "SPHINCS+"
|
||||
|
||||
#define CRYPTO_SECRETKEYBYTES SPX_SK_BYTES
|
||||
#define CRYPTO_PUBLICKEYBYTES SPX_PK_BYTES
|
||||
#define CRYPTO_BYTES SPX_BYTES
|
||||
#define CRYPTO_SEEDBYTES 3*SPX_N
|
||||
|
||||
// We only need this header for the macros that define keys and signature length, we don't need these fonction
|
||||
#ifdef VYBUILD_DEFINE_CRYPTOS_FUNCTION_FROM_HEADER
|
||||
/*
|
||||
* Returns the length of a secret key, in bytes
|
||||
*/
|
||||
unsigned long long crypto_sign_secretkeybytes(void);
|
||||
|
||||
/*
|
||||
* Returns the length of a public key, in bytes
|
||||
*/
|
||||
unsigned long long crypto_sign_publickeybytes(void);
|
||||
|
||||
/*
|
||||
* Returns the length of a signature, in bytes
|
||||
*/
|
||||
unsigned long long crypto_sign_bytes(void);
|
||||
|
||||
/*
|
||||
* Returns the length of the seed required to generate a key pair, in bytes
|
||||
*/
|
||||
unsigned long long crypto_sign_seedbytes(void);
|
||||
|
||||
/*
|
||||
* Generates a SPHINCS+ key pair given a seed.
|
||||
* Format sk: [SK_SEED || SK_PRF || PUB_SEED || root]
|
||||
* Format pk: [root || PUB_SEED]
|
||||
*/
|
||||
int crypto_sign_seed_keypair(unsigned char *pk, unsigned char *sk,
|
||||
const unsigned char *seed);
|
||||
|
||||
/*
|
||||
* Generates a SPHINCS+ key pair.
|
||||
* Format sk: [SK_SEED || SK_PRF || PUB_SEED || root]
|
||||
* Format pk: [root || PUB_SEED]
|
||||
*/
|
||||
int crypto_sign_keypair(unsigned char *pk, unsigned char *sk);
|
||||
|
||||
/**
|
||||
* Returns an array containing a detached signature.
|
||||
*/
|
||||
int crypto_sign_signature(uint8_t *sig, size_t *siglen,
|
||||
const uint8_t *m, size_t mlen, const uint8_t *sk);
|
||||
|
||||
/**
|
||||
* Verifies a detached signature and message under a given public key.
|
||||
*/
|
||||
int crypto_sign_verify(const uint8_t *sig, size_t siglen,
|
||||
const uint8_t *m, size_t mlen, const uint8_t *pk);
|
||||
|
||||
/**
|
||||
* Returns an array containing the signature followed by the message.
|
||||
*/
|
||||
int crypto_sign(unsigned char *sm, unsigned long long *smlen,
|
||||
const unsigned char *m, unsigned long long mlen,
|
||||
const unsigned char *sk);
|
||||
|
||||
/**
|
||||
* Verifies a given signature-message pair under a given public key.
|
||||
*/
|
||||
int crypto_sign_open(unsigned char *m, unsigned long long *mlen,
|
||||
const unsigned char *sm, unsigned long long smlen,
|
||||
const unsigned char *pk);
|
||||
|
||||
#endif
|
||||
#endif
|
||||
2
vybuild/build.sh
Executable file
2
vybuild/build.sh
Executable file
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: MPL-2.0
|
||||
g++ -I. vybuild/vybuild.cpp vybuild/vybuild-actions.cpp vybuild/vybuild-parser.cpp vybuild/vybuild-vars.cpp vybuild/vybuild-cache.cpp vybuild/vybuild-vyld.cpp vybuild/vybuild-condition.cpp vybuild/vybuild-fat32.cpp vybuild/vybuild-disk.cpp vybuild/xxhash.c -std=c++20 -lz -luuid -o vybuild/vybuild
|
||||
1260
vybuild/elfio.hpp
Normal file
1260
vybuild/elfio.hpp
Normal file
File diff suppressed because it is too large
Load Diff
1564
vybuild/elfio/elf_types.hpp
Normal file
1564
vybuild/elfio/elf_types.hpp
Normal file
File diff suppressed because it is too large
Load Diff
119
vybuild/elfio/elfio_array.hpp
Normal file
119
vybuild/elfio/elfio_array.hpp
Normal file
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_ARRAY_HPP
|
||||
#define ELFIO_ARRAY_HPP
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Template class for accessing array sections
|
||||
template <class S, typename T> class array_section_accessor_template
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
// Constructor
|
||||
explicit array_section_accessor_template( const elfio& elf_file,
|
||||
S* section );
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Returns the number of entries in the array section
|
||||
Elf_Xword get_entries_num() const;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Retrieves an entry from the array section
|
||||
bool get_entry( Elf_Xword index, Elf64_Addr& address ) const;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Adds an entry to the array section
|
||||
void add_entry( Elf64_Addr address );
|
||||
|
||||
private:
|
||||
//------------------------------------------------------------------------------
|
||||
// Reference to the ELF file
|
||||
const elfio& elf_file;
|
||||
//------------------------------------------------------------------------------
|
||||
// Pointer to the array section
|
||||
S* array_section;
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Constructor
|
||||
template <class S, typename T>
|
||||
array_section_accessor_template<S, T>::array_section_accessor_template(
|
||||
const elfio& elf_file, S* section )
|
||||
: elf_file( elf_file ), array_section( section )
|
||||
{
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Returns the number of entries in the array section
|
||||
template <class S, typename T>
|
||||
Elf_Xword array_section_accessor_template<S, T>::get_entries_num() const
|
||||
{
|
||||
Elf_Xword entry_size = sizeof( T );
|
||||
return array_section->get_size() / entry_size;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Retrieves an entry from the array section
|
||||
template <class S, typename T>
|
||||
bool array_section_accessor_template<S, T>::get_entry(
|
||||
Elf_Xword index, Elf64_Addr& address ) const
|
||||
{
|
||||
if ( index >= get_entries_num() ) { // Is index valid
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
const T temp = *reinterpret_cast<const T*>( array_section->get_data() +
|
||||
index * sizeof( T ) );
|
||||
address = ( *convertor )( temp );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Adds an entry to the array section
|
||||
template <class S, typename T>
|
||||
void array_section_accessor_template<S, T>::add_entry( Elf64_Addr address )
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
T temp = ( *convertor )( (T)address );
|
||||
array_section->append_data( reinterpret_cast<char*>( &temp ),
|
||||
sizeof( temp ) );
|
||||
}
|
||||
|
||||
// Type aliases for array section accessors
|
||||
template <typename T = Elf32_Word>
|
||||
using array_section_accessor = array_section_accessor_template<section, T>;
|
||||
template <typename T = Elf32_Word>
|
||||
using const_array_section_accessor =
|
||||
array_section_accessor_template<const section, T>;
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_ARRAY_HPP
|
||||
1388
vybuild/elfio/elfio_dump.hpp
Normal file
1388
vybuild/elfio/elfio_dump.hpp
Normal file
File diff suppressed because it is too large
Load Diff
300
vybuild/elfio/elfio_dynamic.hpp
Normal file
300
vybuild/elfio/elfio_dynamic.hpp
Normal file
@@ -0,0 +1,300 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_DYNAMIC_HPP
|
||||
#define ELFIO_DYNAMIC_HPP
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Template class for accessing dynamic sections
|
||||
template <class S> class dynamic_section_accessor_template
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
// Constructor
|
||||
explicit dynamic_section_accessor_template( const elfio& elf_file,
|
||||
S* section )
|
||||
: elf_file( elf_file ), dynamic_section( section ), entries_num( 0 )
|
||||
{
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Returns the number of entries in the dynamic section
|
||||
Elf_Xword get_entries_num() const
|
||||
{
|
||||
size_t needed_entry_size = -1;
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
needed_entry_size = sizeof( Elf32_Dyn );
|
||||
}
|
||||
else {
|
||||
needed_entry_size = sizeof( Elf64_Dyn );
|
||||
}
|
||||
|
||||
if ( ( 0 == entries_num ) &&
|
||||
( 0 != dynamic_section->get_entry_size() &&
|
||||
dynamic_section->get_entry_size() >= needed_entry_size ) ) {
|
||||
entries_num =
|
||||
dynamic_section->get_size() / dynamic_section->get_entry_size();
|
||||
Elf_Xword i;
|
||||
Elf_Xword tag = DT_NULL;
|
||||
Elf_Xword value = 0;
|
||||
std::string str;
|
||||
for ( i = 0; i < entries_num; i++ ) {
|
||||
get_entry( i, tag, value, str );
|
||||
if ( tag == DT_NULL )
|
||||
break;
|
||||
}
|
||||
entries_num = std::min<Elf_Xword>( entries_num, i + 1 );
|
||||
}
|
||||
|
||||
return entries_num;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Retrieves an entry from the dynamic section
|
||||
bool get_entry( Elf_Xword index,
|
||||
Elf_Xword& tag,
|
||||
Elf_Xword& value,
|
||||
std::string& str ) const
|
||||
{
|
||||
if ( index >= get_entries_num() ) { // Is index valid
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
generic_get_entry_dyn<Elf32_Dyn>( index, tag, value );
|
||||
}
|
||||
else {
|
||||
generic_get_entry_dyn<Elf64_Dyn>( index, tag, value );
|
||||
}
|
||||
|
||||
// If the tag has a string table reference - prepare the string
|
||||
if ( tag == DT_NEEDED || tag == DT_SONAME || tag == DT_RPATH ||
|
||||
tag == DT_RUNPATH ) {
|
||||
string_section_accessor strsec(
|
||||
elf_file.sections[get_string_table_index()] );
|
||||
const char* result = strsec.get_string( (Elf_Word)value );
|
||||
if ( nullptr == result ) {
|
||||
str.clear();
|
||||
return false;
|
||||
}
|
||||
str = result;
|
||||
}
|
||||
else {
|
||||
str.clear();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Adds an entry to the dynamic section
|
||||
void add_entry( Elf_Xword tag, Elf_Xword value )
|
||||
{
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
generic_add_entry_dyn<Elf32_Dyn>( tag, value );
|
||||
}
|
||||
else {
|
||||
generic_add_entry_dyn<Elf64_Dyn>( tag, value );
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Adds an entry with a string value to the dynamic section
|
||||
void add_entry( Elf_Xword tag, const std::string& str )
|
||||
{
|
||||
string_section_accessor strsec(
|
||||
elf_file.sections[get_string_table_index()] );
|
||||
Elf_Xword value = strsec.add_string( str );
|
||||
add_entry( tag, value );
|
||||
}
|
||||
|
||||
private:
|
||||
//------------------------------------------------------------------------------
|
||||
// Returns the index of the string table
|
||||
Elf_Half get_string_table_index() const
|
||||
{
|
||||
return (Elf_Half)dynamic_section->get_link();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Retrieves a generic entry from the dynamic section
|
||||
template <class T>
|
||||
void generic_get_entry_dyn( Elf_Xword index,
|
||||
Elf_Xword& tag,
|
||||
Elf_Xword& value ) const
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
// Check unusual case when dynamic section has no data
|
||||
if ( dynamic_section->get_data() == nullptr ||
|
||||
dynamic_section->get_entry_size() < sizeof( T ) ) {
|
||||
tag = DT_NULL;
|
||||
value = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for integer overflow in size calculation
|
||||
if ( index > ( dynamic_section->get_size() /
|
||||
dynamic_section->get_entry_size() ) -
|
||||
1 ) {
|
||||
tag = DT_NULL;
|
||||
value = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for integer overflow in pointer arithmetic
|
||||
Elf_Xword offset = index * dynamic_section->get_entry_size();
|
||||
if ( offset > dynamic_section->get_size() - sizeof( T ) ) {
|
||||
tag = DT_NULL;
|
||||
value = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const T* pEntry =
|
||||
reinterpret_cast<const T*>( dynamic_section->get_data() + offset );
|
||||
tag = ( *convertor )( pEntry->d_tag );
|
||||
switch ( tag ) {
|
||||
case DT_NULL:
|
||||
case DT_SYMBOLIC:
|
||||
case DT_TEXTREL:
|
||||
case DT_BIND_NOW:
|
||||
value = 0;
|
||||
break;
|
||||
case DT_NEEDED:
|
||||
case DT_PLTRELSZ:
|
||||
case DT_RELASZ:
|
||||
case DT_RELAENT:
|
||||
case DT_STRSZ:
|
||||
case DT_SYMENT:
|
||||
case DT_SONAME:
|
||||
case DT_RPATH:
|
||||
case DT_RELSZ:
|
||||
case DT_RELENT:
|
||||
case DT_PLTREL:
|
||||
case DT_INIT_ARRAYSZ:
|
||||
case DT_FINI_ARRAYSZ:
|
||||
case DT_RUNPATH:
|
||||
case DT_FLAGS:
|
||||
case DT_PREINIT_ARRAYSZ:
|
||||
value = ( *convertor )( pEntry->d_un.d_val );
|
||||
break;
|
||||
case DT_PLTGOT:
|
||||
case DT_HASH:
|
||||
case DT_STRTAB:
|
||||
case DT_SYMTAB:
|
||||
case DT_RELA:
|
||||
case DT_INIT:
|
||||
case DT_FINI:
|
||||
case DT_REL:
|
||||
case DT_DEBUG:
|
||||
case DT_JMPREL:
|
||||
case DT_INIT_ARRAY:
|
||||
case DT_FINI_ARRAY:
|
||||
case DT_PREINIT_ARRAY:
|
||||
default:
|
||||
value = ( *convertor )( pEntry->d_un.d_ptr );
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Adds a generic entry to the dynamic section
|
||||
template <class T>
|
||||
void generic_add_entry_dyn( Elf_Xword tag, Elf_Xword value )
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
T entry;
|
||||
|
||||
switch ( tag ) {
|
||||
case DT_NULL:
|
||||
case DT_SYMBOLIC:
|
||||
case DT_TEXTREL:
|
||||
case DT_BIND_NOW:
|
||||
entry.d_un.d_val =
|
||||
( *convertor )( decltype( entry.d_un.d_val )( 0 ) );
|
||||
break;
|
||||
case DT_NEEDED:
|
||||
case DT_PLTRELSZ:
|
||||
case DT_RELASZ:
|
||||
case DT_RELAENT:
|
||||
case DT_STRSZ:
|
||||
case DT_SYMENT:
|
||||
case DT_SONAME:
|
||||
case DT_RPATH:
|
||||
case DT_RELSZ:
|
||||
case DT_RELENT:
|
||||
case DT_PLTREL:
|
||||
case DT_INIT_ARRAYSZ:
|
||||
case DT_FINI_ARRAYSZ:
|
||||
case DT_RUNPATH:
|
||||
case DT_FLAGS:
|
||||
case DT_PREINIT_ARRAYSZ:
|
||||
entry.d_un.d_val =
|
||||
( *convertor )( decltype( entry.d_un.d_val )( value ) );
|
||||
break;
|
||||
case DT_PLTGOT:
|
||||
case DT_HASH:
|
||||
case DT_STRTAB:
|
||||
case DT_SYMTAB:
|
||||
case DT_RELA:
|
||||
case DT_INIT:
|
||||
case DT_FINI:
|
||||
case DT_REL:
|
||||
case DT_DEBUG:
|
||||
case DT_JMPREL:
|
||||
case DT_INIT_ARRAY:
|
||||
case DT_FINI_ARRAY:
|
||||
case DT_PREINIT_ARRAY:
|
||||
default:
|
||||
entry.d_un.d_ptr =
|
||||
( *convertor )( decltype( entry.d_un.d_val )( value ) );
|
||||
break;
|
||||
}
|
||||
|
||||
entry.d_tag = ( *convertor )( decltype( entry.d_tag )( tag ) );
|
||||
|
||||
dynamic_section->append_data( reinterpret_cast<char*>( &entry ),
|
||||
sizeof( entry ) );
|
||||
}
|
||||
|
||||
private:
|
||||
// Reference to the ELF file
|
||||
const elfio& elf_file;
|
||||
// Pointer to the dynamic section
|
||||
S* dynamic_section;
|
||||
// Number of entries in the dynamic section
|
||||
mutable Elf_Xword entries_num;
|
||||
};
|
||||
|
||||
// Type aliases for dynamic section accessors
|
||||
using dynamic_section_accessor = dynamic_section_accessor_template<section>;
|
||||
using const_dynamic_section_accessor =
|
||||
dynamic_section_accessor_template<const section>;
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_DYNAMIC_HPP
|
||||
192
vybuild/elfio/elfio_header.hpp
Normal file
192
vybuild/elfio/elfio_header.hpp
Normal file
@@ -0,0 +1,192 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELF_HEADER_HPP
|
||||
#define ELF_HEADER_HPP
|
||||
|
||||
#include <iostream>
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
/**
|
||||
* @class elf_header
|
||||
* @brief Abstract base class for ELF header.
|
||||
*/
|
||||
class elf_header
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Virtual destructor.
|
||||
*/
|
||||
virtual ~elf_header() = default;
|
||||
|
||||
/**
|
||||
* @brief Load ELF header from stream.
|
||||
* @param stream Input stream.
|
||||
* @return True if successful, false otherwise.
|
||||
*/
|
||||
virtual bool load( std::istream& stream ) = 0;
|
||||
|
||||
/**
|
||||
* @brief Save ELF header to stream.
|
||||
* @param stream Output stream.
|
||||
* @return True if successful, false otherwise.
|
||||
*/
|
||||
virtual bool save( std::ostream& stream ) const = 0;
|
||||
|
||||
// ELF header functions
|
||||
ELFIO_GET_ACCESS_DECL( unsigned char, class );
|
||||
ELFIO_GET_ACCESS_DECL( unsigned char, elf_version );
|
||||
ELFIO_GET_ACCESS_DECL( unsigned char, encoding );
|
||||
ELFIO_GET_ACCESS_DECL( Elf_Half, header_size );
|
||||
ELFIO_GET_ACCESS_DECL( Elf_Half, section_entry_size );
|
||||
ELFIO_GET_ACCESS_DECL( Elf_Half, segment_entry_size );
|
||||
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, version );
|
||||
ELFIO_GET_SET_ACCESS_DECL( unsigned char, os_abi );
|
||||
ELFIO_GET_SET_ACCESS_DECL( unsigned char, abi_version );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Half, type );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Half, machine );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, flags );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, entry );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Half, sections_num );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf64_Off, sections_offset );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Half, segments_num );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf64_Off, segments_offset );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Half, section_name_str_index );
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct elf_header_impl_types
|
||||
* @brief Template specialization for ELF header implementation types.
|
||||
*/
|
||||
template <class T> struct elf_header_impl_types;
|
||||
template <> struct elf_header_impl_types<Elf32_Ehdr>
|
||||
{
|
||||
using Phdr_type = Elf32_Phdr;
|
||||
using Shdr_type = Elf32_Shdr;
|
||||
static const unsigned char file_class = ELFCLASS32;
|
||||
};
|
||||
template <> struct elf_header_impl_types<Elf64_Ehdr>
|
||||
{
|
||||
using Phdr_type = Elf64_Phdr;
|
||||
using Shdr_type = Elf64_Shdr;
|
||||
static const unsigned char file_class = ELFCLASS64;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class elf_header_impl
|
||||
* @brief Template class for ELF header implementation.
|
||||
*/
|
||||
template <class T> class elf_header_impl : public elf_header
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor.
|
||||
* @param convertor Endianness convertor.
|
||||
* @param encoding Encoding type.
|
||||
* @param translator Address translator.
|
||||
*/
|
||||
elf_header_impl( std::shared_ptr<endianness_convertor> convertor,
|
||||
unsigned char encoding,
|
||||
std::shared_ptr<address_translator> translator )
|
||||
: convertor( convertor ), translator( translator )
|
||||
{
|
||||
header.e_ident[EI_MAG0] = ELFMAG0;
|
||||
header.e_ident[EI_MAG1] = ELFMAG1;
|
||||
header.e_ident[EI_MAG2] = ELFMAG2;
|
||||
header.e_ident[EI_MAG3] = ELFMAG3;
|
||||
header.e_ident[EI_CLASS] = elf_header_impl_types<T>::file_class;
|
||||
header.e_ident[EI_DATA] = encoding;
|
||||
header.e_ident[EI_VERSION] = EV_CURRENT;
|
||||
header.e_version = ( *convertor )( (Elf_Word)EV_CURRENT );
|
||||
header.e_ehsize = ( sizeof( header ) );
|
||||
header.e_ehsize = ( *convertor )( header.e_ehsize );
|
||||
header.e_shstrndx = ( *convertor )( (Elf_Half)1 );
|
||||
header.e_phentsize =
|
||||
sizeof( typename elf_header_impl_types<T>::Phdr_type );
|
||||
header.e_shentsize =
|
||||
sizeof( typename elf_header_impl_types<T>::Shdr_type );
|
||||
header.e_phentsize = ( *convertor )( header.e_phentsize );
|
||||
header.e_shentsize = ( *convertor )( header.e_shentsize );
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Load ELF header from stream.
|
||||
* @param stream Input stream.
|
||||
* @return True if successful, false otherwise.
|
||||
*/
|
||||
bool load( std::istream& stream ) override
|
||||
{
|
||||
stream.seekg( ( *translator )[0] );
|
||||
stream.read( reinterpret_cast<char*>( &header ), sizeof( header ) );
|
||||
|
||||
return ( stream.gcount() == sizeof( header ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Save ELF header to stream.
|
||||
* @param stream Output stream.
|
||||
* @return True if successful, false otherwise.
|
||||
*/
|
||||
bool save( std::ostream& stream ) const override
|
||||
{
|
||||
stream.seekp( ( *translator )[0] );
|
||||
stream.write( reinterpret_cast<const char*>( &header ),
|
||||
sizeof( header ) );
|
||||
|
||||
return stream.good();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// ELF header functions
|
||||
ELFIO_GET_ACCESS( unsigned char, class, header.e_ident[EI_CLASS] );
|
||||
ELFIO_GET_ACCESS( unsigned char, elf_version, header.e_ident[EI_VERSION] );
|
||||
ELFIO_GET_ACCESS( unsigned char, encoding, header.e_ident[EI_DATA] );
|
||||
ELFIO_GET_ACCESS( Elf_Half, header_size, header.e_ehsize );
|
||||
ELFIO_GET_ACCESS( Elf_Half, section_entry_size, header.e_shentsize );
|
||||
ELFIO_GET_ACCESS( Elf_Half, segment_entry_size, header.e_phentsize );
|
||||
|
||||
ELFIO_GET_SET_ACCESS( Elf_Word, version, header.e_version );
|
||||
ELFIO_GET_SET_ACCESS( unsigned char, os_abi, header.e_ident[EI_OSABI] );
|
||||
ELFIO_GET_SET_ACCESS( unsigned char,
|
||||
abi_version,
|
||||
header.e_ident[EI_ABIVERSION] );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Half, type, header.e_type );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Half, machine, header.e_machine );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Word, flags, header.e_flags );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Half, section_name_str_index, header.e_shstrndx );
|
||||
ELFIO_GET_SET_ACCESS( Elf64_Addr, entry, header.e_entry );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Half, sections_num, header.e_shnum );
|
||||
ELFIO_GET_SET_ACCESS( Elf64_Off, sections_offset, header.e_shoff );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Half, segments_num, header.e_phnum );
|
||||
ELFIO_GET_SET_ACCESS( Elf64_Off, segments_offset, header.e_phoff );
|
||||
|
||||
private:
|
||||
T header = {};
|
||||
std::shared_ptr<endianness_convertor> convertor = nullptr;
|
||||
std::shared_ptr<address_translator> translator = nullptr;
|
||||
};
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELF_HEADER_HPP
|
||||
168
vybuild/elfio/elfio_modinfo.hpp
Normal file
168
vybuild/elfio/elfio_modinfo.hpp
Normal file
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_MODINFO_HPP
|
||||
#define ELFIO_MODINFO_HPP
|
||||
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
/**
|
||||
* @class modinfo_section_accessor_template
|
||||
* @brief A template class to access modinfo section.
|
||||
*
|
||||
* @tparam S The section type.
|
||||
*/
|
||||
template <class S> class modinfo_section_accessor_template
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
/**
|
||||
* @brief Construct a new modinfo section accessor template object.
|
||||
*
|
||||
* @param section The section to be accessed.
|
||||
*/
|
||||
explicit modinfo_section_accessor_template( S* section )
|
||||
: modinfo_section( section )
|
||||
{
|
||||
process_section();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
/**
|
||||
* @brief Get the number of attributes.
|
||||
*
|
||||
* @return Elf_Word The number of attributes.
|
||||
*/
|
||||
Elf_Word get_attribute_num() const { return (Elf_Word)content.size(); }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
/**
|
||||
* @brief Get the attribute by index.
|
||||
*
|
||||
* @param no The index of the attribute.
|
||||
* @param field The field name of the attribute.
|
||||
* @param value The value of the attribute.
|
||||
* @return true If the attribute is found.
|
||||
* @return false If the attribute is not found.
|
||||
*/
|
||||
bool
|
||||
get_attribute( Elf_Word no, std::string& field, std::string& value ) const
|
||||
{
|
||||
if ( no < content.size() ) {
|
||||
field = content[no].first;
|
||||
value = content[no].second;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
/**
|
||||
* @brief Get the attribute by field name.
|
||||
*
|
||||
* @param field_name The field name of the attribute.
|
||||
* @param value The value of the attribute.
|
||||
* @return true If the attribute is found.
|
||||
* @return false If the attribute is not found.
|
||||
*/
|
||||
bool get_attribute( const std::string_view& field_name,
|
||||
std::string& value ) const
|
||||
{
|
||||
for ( const auto& [first, second] : content ) {
|
||||
if ( field_name == first ) {
|
||||
value = second;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
/**
|
||||
* @brief Add a new attribute.
|
||||
*
|
||||
* @param field The field name of the attribute.
|
||||
* @param value The value of the attribute.
|
||||
* @return Elf_Word The position of the new attribute.
|
||||
*/
|
||||
Elf_Word add_attribute( const std::string& field, const std::string& value )
|
||||
{
|
||||
Elf_Word current_position = 0;
|
||||
|
||||
if ( modinfo_section ) {
|
||||
// Strings are addeded to the end of the current section data
|
||||
current_position = (Elf_Word)modinfo_section->get_size();
|
||||
|
||||
std::string attribute = field + "=" + value;
|
||||
|
||||
modinfo_section->append_data( attribute + '\0' );
|
||||
content.emplace_back( field, value );
|
||||
}
|
||||
|
||||
return current_position;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
/**
|
||||
* @brief Process the section to extract attributes.
|
||||
*/
|
||||
void process_section()
|
||||
{
|
||||
const char* pdata = modinfo_section->get_data();
|
||||
if ( pdata ) {
|
||||
ELFIO::Elf_Xword i = 0;
|
||||
while ( i < modinfo_section->get_size() ) {
|
||||
while ( i < modinfo_section->get_size() && !pdata[i] )
|
||||
i++;
|
||||
if ( i < modinfo_section->get_size() ) {
|
||||
std::string info = pdata + i;
|
||||
size_t loc = info.find( '=' );
|
||||
content.emplace_back( info.substr( 0, loc ),
|
||||
info.substr( loc + 1 ) );
|
||||
|
||||
i += info.length();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
S* modinfo_section; ///< The section to be accessed.
|
||||
std::vector<std::pair<std::string, std::string>>
|
||||
content; ///< The list of attributes.
|
||||
};
|
||||
|
||||
using modinfo_section_accessor = modinfo_section_accessor_template<section>;
|
||||
using const_modinfo_section_accessor =
|
||||
modinfo_section_accessor_template<const section>;
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_MODINFO_HPP
|
||||
208
vybuild/elfio/elfio_note.hpp
Normal file
208
vybuild/elfio/elfio_note.hpp
Normal file
@@ -0,0 +1,208 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_NOTE_HPP
|
||||
#define ELFIO_NOTE_HPP
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// There are discrepancies in documentations. SCO documentation
|
||||
// (http://www.sco.com/developers/gabi/latest/ch5.pheader.html#note_section)
|
||||
// requires 8 byte entries alignment for 64-bit ELF file,
|
||||
// but Oracle's definition uses the same structure
|
||||
// for 32-bit and 64-bit formats.
|
||||
// (https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter6-18048.html)
|
||||
//
|
||||
// It looks like EM_X86_64 Linux implementation is similar to Oracle's
|
||||
// definition. Therefore, the same alignment works for both formats
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class note_section_accessor_template
|
||||
//! \brief Class for accessing note section data
|
||||
template <class S, Elf_Xword ( S::*F_get_size )() const>
|
||||
class note_section_accessor_template
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Constructor
|
||||
//! \param elf_file Reference to the ELF file
|
||||
//! \param section Pointer to the section
|
||||
explicit note_section_accessor_template( const elfio& elf_file, S* section )
|
||||
: elf_file( elf_file ), notes( section )
|
||||
{
|
||||
process_section();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the number of notes
|
||||
//! \return Number of notes
|
||||
Elf_Word get_notes_num() const
|
||||
{
|
||||
return (Elf_Word)note_start_positions.size();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get a note
|
||||
//! \param index Index of the note
|
||||
//! \param type Type of the note
|
||||
//! \param name Name of the note
|
||||
//! \param desc Pointer to the descriptor
|
||||
//! \param descSize Size of the descriptor
|
||||
//! \return True if successful, false otherwise
|
||||
bool get_note( Elf_Word index,
|
||||
Elf_Word& type,
|
||||
std::string& name,
|
||||
char*& desc,
|
||||
Elf_Word& descSize ) const
|
||||
{
|
||||
if ( index >= ( notes->*F_get_size )() ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* pData = notes->get_data() + note_start_positions[index];
|
||||
int align = sizeof( Elf_Word );
|
||||
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
type =
|
||||
( *convertor )( *(const Elf_Word*)( pData + 2 * (size_t)align ) );
|
||||
Elf_Word namesz = ( *convertor )( *(const Elf_Word*)( pData ) );
|
||||
descSize =
|
||||
( *convertor )( *(const Elf_Word*)( pData + sizeof( namesz ) ) );
|
||||
|
||||
Elf_Xword max_name_size =
|
||||
( notes->*F_get_size )() - note_start_positions[index];
|
||||
if ( namesz < 1 || namesz > max_name_size ||
|
||||
(Elf_Xword)namesz + descSize > max_name_size ) {
|
||||
return false;
|
||||
}
|
||||
name.assign( pData + 3 * (size_t)align, namesz - 1 );
|
||||
if ( 0 == descSize ) {
|
||||
desc = nullptr;
|
||||
}
|
||||
else {
|
||||
desc = const_cast<char*>( pData + 3 * (size_t)align +
|
||||
( ( namesz + align - 1 ) / align ) *
|
||||
(size_t)align );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add a note
|
||||
//! \param type Type of the note
|
||||
//! \param name Name of the note
|
||||
//! \param desc Pointer to the descriptor
|
||||
//! \param descSize Size of the descriptor
|
||||
void add_note( Elf_Word type,
|
||||
const std::string& name,
|
||||
const char* desc,
|
||||
Elf_Word descSize )
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
int align = sizeof( Elf_Word );
|
||||
Elf_Word nameLen = (Elf_Word)name.size() + 1;
|
||||
Elf_Word nameLenConv = ( *convertor )( nameLen );
|
||||
std::string buffer( reinterpret_cast<char*>( &nameLenConv ), align );
|
||||
Elf_Word descSizeConv = ( *convertor )( descSize );
|
||||
|
||||
buffer.append( reinterpret_cast<char*>( &descSizeConv ), align );
|
||||
type = ( *convertor )( type );
|
||||
buffer.append( reinterpret_cast<char*>( &type ), align );
|
||||
buffer.append( name );
|
||||
buffer.append( 1, '\x00' );
|
||||
const char pad[] = { '\0', '\0', '\0', '\0' };
|
||||
if ( nameLen % align != 0 ) {
|
||||
buffer.append( pad, (size_t)align - nameLen % align );
|
||||
}
|
||||
if ( desc != nullptr && descSize != 0 ) {
|
||||
buffer.append( desc, descSize );
|
||||
if ( descSize % align != 0 ) {
|
||||
buffer.append( pad, (size_t)align - descSize % align );
|
||||
}
|
||||
}
|
||||
|
||||
note_start_positions.emplace_back( ( notes->*F_get_size )() );
|
||||
notes->append_data( buffer );
|
||||
}
|
||||
|
||||
private:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Process the section to extract note start positions
|
||||
void process_section()
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
const char* data = notes->get_data();
|
||||
Elf_Xword size = ( notes->*F_get_size )();
|
||||
Elf_Xword current = 0;
|
||||
|
||||
note_start_positions.clear();
|
||||
|
||||
// Is it empty?
|
||||
if ( nullptr == data || 0 == size ) {
|
||||
return;
|
||||
}
|
||||
|
||||
Elf_Word align = sizeof( Elf_Word );
|
||||
while ( current + (Elf_Xword)3 * align <= size ) {
|
||||
Elf_Word namesz =
|
||||
( *convertor )( *(const Elf_Word*)( data + current ) );
|
||||
Elf_Word descsz = ( *convertor )(
|
||||
*(const Elf_Word*)( data + current + sizeof( namesz ) ) );
|
||||
Elf_Word advance =
|
||||
(Elf_Xword)3 * sizeof( Elf_Word ) +
|
||||
( ( namesz + align - 1 ) / align ) * (Elf_Xword)align +
|
||||
( ( descsz + align - 1 ) / align ) * (Elf_Xword)align;
|
||||
if ( namesz < size && descsz < size && current + advance <= size ) {
|
||||
note_start_positions.emplace_back( current );
|
||||
}
|
||||
else {
|
||||
break;
|
||||
}
|
||||
|
||||
current += advance;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
const elfio& elf_file; //!< Reference to the ELF file
|
||||
S* notes; //!< Pointer to the section or segment
|
||||
std::vector<Elf_Xword>
|
||||
note_start_positions; //!< Vector of note start positions
|
||||
};
|
||||
|
||||
using note_section_accessor =
|
||||
note_section_accessor_template<section, §ion::get_size>;
|
||||
using const_note_section_accessor =
|
||||
note_section_accessor_template<const section, §ion::get_size>;
|
||||
using note_segment_accessor =
|
||||
note_section_accessor_template<segment, &segment::get_file_size>;
|
||||
using const_note_segment_accessor =
|
||||
note_section_accessor_template<const segment, &segment::get_file_size>;
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_NOTE_HPP
|
||||
596
vybuild/elfio/elfio_relocation.hpp
Normal file
596
vybuild/elfio/elfio_relocation.hpp
Normal file
@@ -0,0 +1,596 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_RELOCATION_HPP
|
||||
#define ELFIO_RELOCATION_HPP
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
template <typename T> struct get_sym_and_type;
|
||||
template <> struct get_sym_and_type<Elf32_Rel>
|
||||
{
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the symbol from the relocation info
|
||||
//! \param info Relocation info
|
||||
//! \return Symbol
|
||||
static int get_r_sym( Elf_Xword info )
|
||||
{
|
||||
return ELF32_R_SYM( (Elf_Word)info );
|
||||
}
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the type from the relocation info
|
||||
//! \param info Relocation info
|
||||
//! \return Type
|
||||
static int get_r_type( Elf_Xword info )
|
||||
{
|
||||
return ELF32_R_TYPE( (Elf_Word)info );
|
||||
}
|
||||
};
|
||||
template <> struct get_sym_and_type<Elf32_Rela>
|
||||
{
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the symbol from the relocation info
|
||||
//! \param info Relocation info
|
||||
//! \return Symbol
|
||||
static int get_r_sym( Elf_Xword info )
|
||||
{
|
||||
return ELF32_R_SYM( (Elf_Word)info );
|
||||
}
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the type from the relocation info
|
||||
//! \param info Relocation info
|
||||
//! \return Type
|
||||
static int get_r_type( Elf_Xword info )
|
||||
{
|
||||
return ELF32_R_TYPE( (Elf_Word)info );
|
||||
}
|
||||
};
|
||||
template <> struct get_sym_and_type<Elf64_Rel>
|
||||
{
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the symbol from the relocation info
|
||||
//! \param info Relocation info
|
||||
//! \return Symbol
|
||||
static int get_r_sym( Elf_Xword info ) { return ELF64_R_SYM( info ); }
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the type from the relocation info
|
||||
//! \param info Relocation info
|
||||
//! \return Type
|
||||
static int get_r_type( Elf_Xword info ) { return ELF64_R_TYPE( info ); }
|
||||
};
|
||||
template <> struct get_sym_and_type<Elf64_Rela>
|
||||
{
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the symbol from the relocation info
|
||||
//! \param info Relocation info
|
||||
//! \return Symbol
|
||||
static int get_r_sym( Elf_Xword info ) { return ELF64_R_SYM( info ); }
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the type from the relocation info
|
||||
//! \param info Relocation info
|
||||
//! \return Type
|
||||
static int get_r_type( Elf_Xword info ) { return ELF64_R_TYPE( info ); }
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class relocation_section_accessor_template
|
||||
//! \brief Class for accessing relocation section data
|
||||
template <class S> class relocation_section_accessor_template
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Constructor
|
||||
//! \param elf_file Reference to the ELF file
|
||||
//! \param section Pointer to the section
|
||||
explicit relocation_section_accessor_template( const elfio& elf_file,
|
||||
S* section )
|
||||
: elf_file( elf_file ), relocation_section( section )
|
||||
{
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the number of entries
|
||||
//! \return Number of entries
|
||||
Elf_Xword get_entries_num() const
|
||||
{
|
||||
Elf_Xword nRet = 0;
|
||||
|
||||
if ( 0 != relocation_section->get_entry_size() ) {
|
||||
nRet = relocation_section->get_size() /
|
||||
relocation_section->get_entry_size();
|
||||
}
|
||||
|
||||
return nRet;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get an entry
|
||||
//! \param index Index of the entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param symbol Symbol of the entry
|
||||
//! \param type Type of the entry
|
||||
//! \param addend Addend of the entry
|
||||
//! \return True if successful, false otherwise
|
||||
bool get_entry( Elf_Xword index,
|
||||
Elf64_Addr& offset,
|
||||
Elf_Word& symbol,
|
||||
unsigned& type,
|
||||
Elf_Sxword& addend ) const
|
||||
{
|
||||
if ( index >= get_entries_num() ) { // Is index valid
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
if ( SHT_REL == relocation_section->get_type() ) {
|
||||
return generic_get_entry_rel<Elf32_Rel>( index, offset, symbol,
|
||||
type, addend );
|
||||
}
|
||||
else if ( SHT_RELA == relocation_section->get_type() ) {
|
||||
return generic_get_entry_rela<Elf32_Rela>(
|
||||
index, offset, symbol, type, addend );
|
||||
}
|
||||
}
|
||||
else {
|
||||
if ( SHT_REL == relocation_section->get_type() ) {
|
||||
return generic_get_entry_rel<Elf64_Rel>( index, offset, symbol,
|
||||
type, addend );
|
||||
}
|
||||
else if ( SHT_RELA == relocation_section->get_type() ) {
|
||||
return generic_get_entry_rela<Elf64_Rela>(
|
||||
index, offset, symbol, type, addend );
|
||||
}
|
||||
}
|
||||
// Unknown relocation section type.
|
||||
return false;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get an entry with additional information
|
||||
//! \param index Index of the entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param symbolValue Value of the symbol
|
||||
//! \param symbolName Name of the symbol
|
||||
//! \param type Type of the entry
|
||||
//! \param addend Addend of the entry
|
||||
//! \param calcValue Calculated value
|
||||
//! \return True if successful, false otherwise
|
||||
bool get_entry( Elf_Xword index,
|
||||
Elf64_Addr& offset,
|
||||
Elf64_Addr& symbolValue,
|
||||
std::string& symbolName,
|
||||
unsigned& type,
|
||||
Elf_Sxword& addend,
|
||||
Elf_Sxword& calcValue ) const
|
||||
{
|
||||
// Do regular job
|
||||
Elf_Word symbol = 0;
|
||||
bool ret = get_entry( index, offset, symbol, type, addend );
|
||||
|
||||
// Find the symbol
|
||||
Elf_Xword size;
|
||||
unsigned char bind;
|
||||
unsigned char symbolType;
|
||||
Elf_Half section;
|
||||
unsigned char other;
|
||||
|
||||
symbol_section_accessor symbols(
|
||||
elf_file, elf_file.sections[get_symbol_table_index()] );
|
||||
ret = ret && symbols.get_symbol( symbol, symbolName, symbolValue, size,
|
||||
bind, symbolType, section, other );
|
||||
|
||||
if ( ret ) { // Was it successful?
|
||||
switch ( type ) {
|
||||
case R_386_NONE: // none
|
||||
calcValue = 0;
|
||||
break;
|
||||
case R_386_32: // S + A
|
||||
calcValue = symbolValue + addend;
|
||||
break;
|
||||
case R_386_PC32: // S + A - P
|
||||
calcValue = symbolValue + addend - offset;
|
||||
break;
|
||||
case R_386_GOT32: // G + A - P
|
||||
calcValue = 0;
|
||||
break;
|
||||
case R_386_PLT32: // L + A - P
|
||||
calcValue = 0;
|
||||
break;
|
||||
case R_386_COPY: // none
|
||||
calcValue = 0;
|
||||
break;
|
||||
case R_386_GLOB_DAT: // S
|
||||
case R_386_JMP_SLOT: // S
|
||||
calcValue = symbolValue;
|
||||
break;
|
||||
case R_386_RELATIVE: // B + A
|
||||
calcValue = addend;
|
||||
break;
|
||||
case R_386_GOTOFF: // S + A - GOT
|
||||
calcValue = 0;
|
||||
break;
|
||||
case R_386_GOTPC: // GOT + A - P
|
||||
calcValue = 0;
|
||||
break;
|
||||
default: // Not recognized symbol!
|
||||
calcValue = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Set an entry
|
||||
//! \param index Index of the entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param symbol Symbol of the entry
|
||||
//! \param type Type of the entry
|
||||
//! \param addend Addend of the entry
|
||||
//! \return True if successful, false otherwise
|
||||
bool set_entry( Elf_Xword index,
|
||||
Elf64_Addr offset,
|
||||
Elf_Word symbol,
|
||||
unsigned type,
|
||||
Elf_Sxword addend )
|
||||
{
|
||||
if ( index >= get_entries_num() ) { // Is index valid
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
if ( SHT_REL == relocation_section->get_type() ) {
|
||||
generic_set_entry_rel<Elf32_Rel>( index, offset, symbol, type,
|
||||
addend );
|
||||
}
|
||||
else if ( SHT_RELA == relocation_section->get_type() ) {
|
||||
generic_set_entry_rela<Elf32_Rela>( index, offset, symbol, type,
|
||||
addend );
|
||||
}
|
||||
}
|
||||
else {
|
||||
if ( SHT_REL == relocation_section->get_type() ) {
|
||||
generic_set_entry_rel<Elf64_Rel>( index, offset, symbol, type,
|
||||
addend );
|
||||
}
|
||||
else if ( SHT_RELA == relocation_section->get_type() ) {
|
||||
generic_set_entry_rela<Elf64_Rela>( index, offset, symbol, type,
|
||||
addend );
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add an entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param info Information of the entry
|
||||
void add_entry( Elf64_Addr offset, Elf_Xword info )
|
||||
{
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
generic_add_entry<Elf32_Rel>( offset, info );
|
||||
}
|
||||
else {
|
||||
generic_add_entry<Elf64_Rel>( offset, info );
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add an entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param symbol Symbol of the entry
|
||||
//! \param type Type of the entry
|
||||
void add_entry( Elf64_Addr offset, Elf_Word symbol, unsigned type )
|
||||
{
|
||||
Elf_Xword info;
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
info = ELF32_R_INFO( (Elf_Xword)symbol, type );
|
||||
}
|
||||
else {
|
||||
info = ELF64_R_INFO( (Elf_Xword)symbol, type );
|
||||
}
|
||||
|
||||
add_entry( offset, info );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add an entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param info Information of the entry
|
||||
//! \param addend Addend of the entry
|
||||
void add_entry( Elf64_Addr offset, Elf_Xword info, Elf_Sxword addend )
|
||||
{
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
generic_add_entry<Elf32_Rela>( offset, info, addend );
|
||||
}
|
||||
else {
|
||||
generic_add_entry<Elf64_Rela>( offset, info, addend );
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add an entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param symbol Symbol of the entry
|
||||
//! \param type Type of the entry
|
||||
//! \param addend Addend of the entry
|
||||
void add_entry( Elf64_Addr offset,
|
||||
Elf_Word symbol,
|
||||
unsigned type,
|
||||
Elf_Sxword addend )
|
||||
{
|
||||
Elf_Xword info;
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
info = ELF32_R_INFO( (Elf_Xword)symbol, type );
|
||||
}
|
||||
else {
|
||||
info = ELF64_R_INFO( (Elf_Xword)symbol, type );
|
||||
}
|
||||
|
||||
add_entry( offset, info, addend );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add an entry with additional information
|
||||
//! \param str_writer String section accessor
|
||||
//! \param str String
|
||||
//! \param sym_writer Symbol section accessor
|
||||
//! \param value Value of the symbol
|
||||
//! \param size Size of the symbol
|
||||
//! \param sym_info Symbol information
|
||||
//! \param other Other information
|
||||
//! \param shndx Section index
|
||||
//! \param offset Offset of the entry
|
||||
//! \param type Type of the entry
|
||||
void add_entry( string_section_accessor str_writer,
|
||||
const char* str,
|
||||
symbol_section_accessor sym_writer,
|
||||
Elf64_Addr value,
|
||||
Elf_Word size,
|
||||
unsigned char sym_info,
|
||||
unsigned char other,
|
||||
Elf_Half shndx,
|
||||
Elf64_Addr offset,
|
||||
unsigned type )
|
||||
{
|
||||
Elf_Word str_index = str_writer.add_string( str );
|
||||
Elf_Word sym_index = sym_writer.add_symbol( str_index, value, size,
|
||||
sym_info, other, shndx );
|
||||
add_entry( offset, sym_index, type );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Swap symbols
|
||||
//! \param first First symbol
|
||||
//! \param second Second symbol
|
||||
void swap_symbols( Elf_Xword first, Elf_Xword second )
|
||||
{
|
||||
Elf64_Addr offset = 0;
|
||||
Elf_Word symbol = 0;
|
||||
unsigned rtype = 0;
|
||||
Elf_Sxword addend = 0;
|
||||
for ( Elf_Word i = 0; i < get_entries_num(); i++ ) {
|
||||
get_entry( i, offset, symbol, rtype, addend );
|
||||
if ( symbol == first ) {
|
||||
set_entry( i, offset, (Elf_Word)second, rtype, addend );
|
||||
}
|
||||
if ( symbol == second ) {
|
||||
set_entry( i, offset, (Elf_Word)first, rtype, addend );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the symbol table index
|
||||
//! \return Symbol table index
|
||||
Elf_Half get_symbol_table_index() const
|
||||
{
|
||||
return (Elf_Half)relocation_section->get_link();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get a generic entry for REL type
|
||||
//! \param index Index of the entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param symbol Symbol of the entry
|
||||
//! \param type Type of the entry
|
||||
//! \param addend Addend of the entry
|
||||
//! \return True if successful, false otherwise
|
||||
template <class T>
|
||||
bool generic_get_entry_rel( Elf_Xword index,
|
||||
Elf64_Addr& offset,
|
||||
Elf_Word& symbol,
|
||||
unsigned& type,
|
||||
Elf_Sxword& addend ) const
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
if ( relocation_section->get_entry_size() < sizeof( T ) ) {
|
||||
return false;
|
||||
}
|
||||
const T* pEntry = reinterpret_cast<const T*>(
|
||||
relocation_section->get_data() +
|
||||
index * relocation_section->get_entry_size() );
|
||||
offset = ( *convertor )( pEntry->r_offset );
|
||||
Elf_Xword tmp = ( *convertor )( pEntry->r_info );
|
||||
symbol = get_sym_and_type<T>::get_r_sym( tmp );
|
||||
type = get_sym_and_type<T>::get_r_type( tmp );
|
||||
addend = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get a generic entry for RELA type
|
||||
//! \param index Index of the entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param symbol Symbol of the entry
|
||||
//! \param type Type of the entry
|
||||
//! \param addend Addend of the entry
|
||||
//! \return True if successful, false otherwise
|
||||
template <class T>
|
||||
bool generic_get_entry_rela( Elf_Xword index,
|
||||
Elf64_Addr& offset,
|
||||
Elf_Word& symbol,
|
||||
unsigned& type,
|
||||
Elf_Sxword& addend ) const
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
if ( relocation_section->get_entry_size() < sizeof( T ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const T* pEntry = reinterpret_cast<const T*>(
|
||||
relocation_section->get_data() +
|
||||
index * relocation_section->get_entry_size() );
|
||||
offset = ( *convertor )( pEntry->r_offset );
|
||||
Elf_Xword tmp = ( *convertor )( pEntry->r_info );
|
||||
symbol = get_sym_and_type<T>::get_r_sym( tmp );
|
||||
type = get_sym_and_type<T>::get_r_type( tmp );
|
||||
addend = ( *convertor )( pEntry->r_addend );
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Set a generic entry for REL type
|
||||
//! \param index Index of the entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param symbol Symbol of the entry
|
||||
//! \param type Type of the entry
|
||||
//! \param addend Addend of the entry
|
||||
template <class T>
|
||||
void generic_set_entry_rel( Elf_Xword index,
|
||||
Elf64_Addr offset,
|
||||
Elf_Word symbol,
|
||||
unsigned type,
|
||||
Elf_Sxword )
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
T* pEntry = const_cast<T*>( reinterpret_cast<const T*>(
|
||||
relocation_section->get_data() +
|
||||
index * relocation_section->get_entry_size() ) );
|
||||
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
pEntry->r_info = ELF32_R_INFO( (Elf_Xword)symbol, type );
|
||||
}
|
||||
else {
|
||||
pEntry->r_info = ELF64_R_INFO( (Elf_Xword)symbol, type );
|
||||
}
|
||||
pEntry->r_offset = decltype( pEntry->r_offset )( offset );
|
||||
pEntry->r_offset = ( *convertor )( pEntry->r_offset );
|
||||
pEntry->r_info = ( *convertor )( pEntry->r_info );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Set a generic entry for RELA type
|
||||
//! \param index Index of the entry
|
||||
//! \param offset Offset of the entry
|
||||
//! \param symbol Symbol of the entry
|
||||
//! \param type Type of the entry
|
||||
//! \param addend Addend of the entry
|
||||
template <class T>
|
||||
void generic_set_entry_rela( Elf_Xword index,
|
||||
Elf64_Addr offset,
|
||||
Elf_Word symbol,
|
||||
unsigned type,
|
||||
Elf_Sxword addend )
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
T* pEntry = const_cast<T*>( reinterpret_cast<const T*>(
|
||||
relocation_section->get_data() +
|
||||
index * relocation_section->get_entry_size() ) );
|
||||
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
pEntry->r_info = ELF32_R_INFO( (Elf_Xword)symbol, type );
|
||||
}
|
||||
else {
|
||||
pEntry->r_info = ELF64_R_INFO( (Elf_Xword)symbol, type );
|
||||
}
|
||||
pEntry->r_offset = decltype( pEntry->r_offset )( offset );
|
||||
pEntry->r_addend = decltype( pEntry->r_addend )( addend );
|
||||
pEntry->r_offset = ( *convertor )( pEntry->r_offset );
|
||||
pEntry->r_info = ( *convertor )( pEntry->r_info );
|
||||
pEntry->r_addend = ( *convertor )( pEntry->r_addend );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add a generic entry for REL type
|
||||
//! \param offset Offset of the entry
|
||||
//! \param info Information of the entry
|
||||
template <class T>
|
||||
void generic_add_entry( Elf64_Addr offset, Elf_Xword info )
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
T entry;
|
||||
entry.r_offset = decltype( entry.r_offset )( offset );
|
||||
entry.r_info = decltype( entry.r_info )( info );
|
||||
entry.r_offset = ( *convertor )( entry.r_offset );
|
||||
entry.r_info = ( *convertor )( entry.r_info );
|
||||
|
||||
relocation_section->append_data( reinterpret_cast<char*>( &entry ),
|
||||
sizeof( entry ) );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add a generic entry for RELA type
|
||||
//! \param offset Offset of the entry
|
||||
//! \param info Information of the entry
|
||||
//! \param addend Addend of the entry
|
||||
template <class T>
|
||||
void
|
||||
generic_add_entry( Elf64_Addr offset, Elf_Xword info, Elf_Sxword addend )
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
T entry;
|
||||
entry.r_offset = offset;
|
||||
entry.r_info = info;
|
||||
entry.r_addend = addend;
|
||||
entry.r_offset = ( *convertor )( entry.r_offset );
|
||||
entry.r_info = ( *convertor )( entry.r_info );
|
||||
entry.r_addend = ( *convertor )( entry.r_addend );
|
||||
|
||||
relocation_section->append_data( reinterpret_cast<char*>( &entry ),
|
||||
sizeof( entry ) );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
const elfio& elf_file;
|
||||
S* relocation_section = nullptr;
|
||||
};
|
||||
|
||||
using relocation_section_accessor =
|
||||
relocation_section_accessor_template<section>;
|
||||
using const_relocation_section_accessor =
|
||||
relocation_section_accessor_template<const section>;
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_RELOCATION_HPP
|
||||
611
vybuild/elfio/elfio_section.hpp
Normal file
611
vybuild/elfio/elfio_section.hpp
Normal file
@@ -0,0 +1,611 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_SECTION_HPP
|
||||
#define ELFIO_SECTION_HPP
|
||||
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <new>
|
||||
#include <limits>
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
/**
|
||||
* @class section
|
||||
* @brief Represents a section in an ELF file.
|
||||
*/
|
||||
class section
|
||||
{
|
||||
friend class elfio;
|
||||
|
||||
public:
|
||||
virtual ~section() = default;
|
||||
|
||||
ELFIO_GET_ACCESS_DECL( Elf_Half, index );
|
||||
ELFIO_GET_SET_ACCESS_DECL( std::string, name );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, flags );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, info );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, link );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, addr_align );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, entry_size );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, address );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, size );
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, name_string_offset );
|
||||
ELFIO_GET_ACCESS_DECL( Elf64_Off, offset );
|
||||
|
||||
/**
|
||||
* @brief Get the data of the section.
|
||||
* @return Pointer to the data.
|
||||
*/
|
||||
virtual const char* get_data() const = 0;
|
||||
|
||||
/**
|
||||
* @brief Free the data of the section.
|
||||
*/
|
||||
virtual void free_data() const = 0;
|
||||
|
||||
/**
|
||||
* @brief Set the data of the section.
|
||||
* @param raw_data Pointer to the raw data.
|
||||
* @param size Size of the data.
|
||||
*/
|
||||
virtual void set_data( const char* raw_data, Elf_Xword size ) = 0;
|
||||
|
||||
/**
|
||||
* @brief Set the data of the section.
|
||||
* @param data String containing the data.
|
||||
*/
|
||||
virtual void set_data( const std::string& data ) = 0;
|
||||
|
||||
/**
|
||||
* @brief Append data to the section.
|
||||
* @param raw_data Pointer to the raw data.
|
||||
* @param size Size of the data.
|
||||
*/
|
||||
virtual void append_data( const char* raw_data, Elf_Xword size ) = 0;
|
||||
|
||||
/**
|
||||
* @brief Append data to the section.
|
||||
* @param data String containing the data.
|
||||
*/
|
||||
virtual void append_data( const std::string& data ) = 0;
|
||||
|
||||
/**
|
||||
* @brief Insert data into the section at a specific position.
|
||||
* @param pos Position to insert the data.
|
||||
* @param raw_data Pointer to the raw data.
|
||||
* @param size Size of the data.
|
||||
*/
|
||||
virtual void
|
||||
insert_data( Elf_Xword pos, const char* raw_data, Elf_Xword size ) = 0;
|
||||
|
||||
/**
|
||||
* @brief Insert data into the section at a specific position.
|
||||
* @param pos Position to insert the data.
|
||||
* @param data String containing the data.
|
||||
*/
|
||||
virtual void insert_data( Elf_Xword pos, const std::string& data ) = 0;
|
||||
|
||||
/**
|
||||
* @brief Get the size of the stream.
|
||||
* @return Size of the stream.
|
||||
*/
|
||||
virtual size_t get_stream_size() const = 0;
|
||||
|
||||
/**
|
||||
* @brief Set the size of the stream.
|
||||
* @param value Size of the stream.
|
||||
*/
|
||||
virtual void set_stream_size( size_t value ) = 0;
|
||||
|
||||
protected:
|
||||
ELFIO_SET_ACCESS_DECL( Elf64_Off, offset );
|
||||
ELFIO_SET_ACCESS_DECL( Elf_Half, index );
|
||||
|
||||
/**
|
||||
* @brief Load the section from a stream.
|
||||
* @param stream Input stream.
|
||||
* @param header_offset Offset of the header.
|
||||
* @param is_lazy Whether to load lazily.
|
||||
* @return True if successful, false otherwise.
|
||||
*/
|
||||
virtual bool load( std::istream& stream,
|
||||
std::streampos header_offset,
|
||||
bool is_lazy ) = 0;
|
||||
|
||||
/**
|
||||
* @brief Save the section to a stream.
|
||||
* @param stream Output stream.
|
||||
* @param header_offset Offset of the header.
|
||||
* @param data_offset Offset of the data.
|
||||
*/
|
||||
virtual void save( std::ostream& stream,
|
||||
std::streampos header_offset,
|
||||
std::streampos data_offset ) = 0;
|
||||
|
||||
/**
|
||||
* @brief Check if the address is initialized.
|
||||
* @return True if initialized, false otherwise.
|
||||
*/
|
||||
virtual bool is_address_initialized() const = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* @class section_impl
|
||||
* @brief Implementation of the section class.
|
||||
* @tparam T Type of the section header.
|
||||
*/
|
||||
template <class T> class section_impl : public section
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor.
|
||||
* @param convertor Pointer to the endianness convertor.
|
||||
* @param translator Pointer to the address translator.
|
||||
* @param compression Shared pointer to the compression interface.
|
||||
*/
|
||||
section_impl( std::shared_ptr<endianness_convertor> convertor,
|
||||
std::shared_ptr<address_translator> translator,
|
||||
std::shared_ptr<compression_interface> compression )
|
||||
: convertor( convertor ), translator( translator ),
|
||||
compression( compression )
|
||||
{
|
||||
}
|
||||
|
||||
// Section info functions
|
||||
ELFIO_GET_SET_ACCESS( Elf_Word, type, header.sh_type );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Xword, flags, header.sh_flags );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Xword, size, header.sh_size );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Word, link, header.sh_link );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Word, info, header.sh_info );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Xword, addr_align, header.sh_addralign );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Xword, entry_size, header.sh_entsize );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Word, name_string_offset, header.sh_name );
|
||||
ELFIO_GET_ACCESS( Elf64_Addr, address, header.sh_addr );
|
||||
|
||||
/**
|
||||
* @brief Get the index of the section.
|
||||
* @return Index of the section.
|
||||
*/
|
||||
Elf_Half get_index() const override { return index; }
|
||||
|
||||
/**
|
||||
* @brief Get the name of the section.
|
||||
* @return Name of the section.
|
||||
*/
|
||||
std::string get_name() const override { return name; }
|
||||
|
||||
/**
|
||||
* @brief Set the name of the section.
|
||||
* @param name_prm Name of the section.
|
||||
*/
|
||||
void set_name( const std::string& name_prm ) override
|
||||
{
|
||||
this->name = name_prm;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Set the address of the section.
|
||||
* @param value Address of the section.
|
||||
*/
|
||||
void set_address( const Elf64_Addr& value ) override
|
||||
{
|
||||
header.sh_addr = decltype( header.sh_addr )( value );
|
||||
header.sh_addr = ( *convertor )( header.sh_addr );
|
||||
is_address_set = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Check if the address is initialized.
|
||||
* @return True if initialized, false otherwise.
|
||||
*/
|
||||
bool is_address_initialized() const override { return is_address_set; }
|
||||
|
||||
/**
|
||||
* @brief Get the data of the section.
|
||||
* @return Pointer to the data.
|
||||
*/
|
||||
const char* get_data() const override
|
||||
{
|
||||
// If data load failed, the stream is corrupt
|
||||
// When lazy loading, attempts to call get_data() on it after initial load are useless
|
||||
// When loading non-lazily, that load_data() will attempt to read data from
|
||||
// the stream specified on load() call, which might be freed by this point
|
||||
if ( !is_loaded && can_be_loaded ) {
|
||||
bool res = load_data();
|
||||
|
||||
if ( !res ) {
|
||||
can_be_loaded = false;
|
||||
}
|
||||
}
|
||||
return data.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Free the data of the section.
|
||||
*/
|
||||
void free_data() const override
|
||||
{
|
||||
if ( is_lazy ) {
|
||||
data.reset( nullptr );
|
||||
is_loaded = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Set the data of the section.
|
||||
* @param raw_data Pointer to the raw data.
|
||||
* @param size Size of the data.
|
||||
*/
|
||||
void set_data( const char* raw_data, Elf_Xword size ) override
|
||||
{
|
||||
if ( get_type() != SHT_NOBITS ) {
|
||||
data = std::unique_ptr<char[]>(
|
||||
new ( std::nothrow ) char[(size_t)size] );
|
||||
if ( nullptr != data.get() && nullptr != raw_data ) {
|
||||
data_size = size;
|
||||
std::copy( raw_data, raw_data + size, data.get() );
|
||||
}
|
||||
else {
|
||||
data_size = 0;
|
||||
}
|
||||
}
|
||||
|
||||
set_size( data_size );
|
||||
if ( translator->empty() ) {
|
||||
set_stream_size( (size_t)data_size );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Set the data of the section.
|
||||
* @param str_data String containing the data.
|
||||
*/
|
||||
void set_data( const std::string& str_data ) override
|
||||
{
|
||||
return set_data( str_data.c_str(), (Elf_Word)str_data.size() );
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Append data to the section.
|
||||
* @param raw_data Pointer to the raw data.
|
||||
* @param size Size of the data.
|
||||
*/
|
||||
void append_data( const char* raw_data, Elf_Xword size ) override
|
||||
{
|
||||
insert_data( get_size(), raw_data, size );
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Append data to the section.
|
||||
* @param str_data String containing the data.
|
||||
*/
|
||||
void append_data( const std::string& str_data ) override
|
||||
{
|
||||
return append_data( str_data.c_str(), (Elf_Word)str_data.size() );
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Insert data into the section at a specific position.
|
||||
* @param pos Position to insert the data.
|
||||
* @param raw_data Pointer to the raw data.
|
||||
* @param size Size of the data.
|
||||
*/
|
||||
void
|
||||
insert_data( Elf_Xword pos, const char* raw_data, Elf_Xword size ) override
|
||||
{
|
||||
if ( get_type() != SHT_NOBITS ) {
|
||||
// Check for valid position
|
||||
if ( pos > get_size() ) {
|
||||
return; // Invalid position
|
||||
}
|
||||
|
||||
// Check for integer overflow in size calculation
|
||||
Elf_Xword new_size = get_size();
|
||||
if ( size > std::numeric_limits<Elf_Xword>::max() - new_size ) {
|
||||
return; // Size would overflow
|
||||
}
|
||||
new_size += size;
|
||||
|
||||
if ( new_size <= data_size ) {
|
||||
char* d = data.get();
|
||||
std::copy_backward( d + pos, d + get_size(),
|
||||
d + get_size() + size );
|
||||
std::copy( raw_data, raw_data + size, d + pos );
|
||||
}
|
||||
else {
|
||||
// Calculate new size with overflow check
|
||||
Elf_Xword new_data_size = data_size;
|
||||
if ( new_data_size >
|
||||
std::numeric_limits<Elf_Xword>::max() / 2 ) {
|
||||
return; // Multiplication would overflow
|
||||
}
|
||||
new_data_size *= 2;
|
||||
if ( size >
|
||||
std::numeric_limits<Elf_Xword>::max() - new_data_size ) {
|
||||
return; // Addition would overflow
|
||||
}
|
||||
new_data_size += size;
|
||||
|
||||
// Check if the size would overflow size_t
|
||||
if ( new_data_size > std::numeric_limits<size_t>::max() ) {
|
||||
return; // Size would overflow size_t
|
||||
}
|
||||
|
||||
std::unique_ptr<char[]> new_data(
|
||||
new ( std::nothrow ) char[(size_t)new_data_size] );
|
||||
|
||||
if ( nullptr != new_data ) {
|
||||
char* d = data.get();
|
||||
std::copy( d, d + pos, new_data.get() );
|
||||
std::copy( raw_data, raw_data + size,
|
||||
new_data.get() + pos );
|
||||
std::copy( d + pos, d + get_size(),
|
||||
new_data.get() + pos + size );
|
||||
data = std::move( new_data );
|
||||
data_size = new_data_size;
|
||||
}
|
||||
else {
|
||||
return; // Allocation failed
|
||||
}
|
||||
}
|
||||
set_size( new_size );
|
||||
if ( translator->empty() ) {
|
||||
set_stream_size( get_stream_size() + (size_t)size );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Insert data into the section at a specific position.
|
||||
* @param pos Position to insert the data.
|
||||
* @param str_data String containing the data.
|
||||
*/
|
||||
void insert_data( Elf_Xword pos, const std::string& str_data ) override
|
||||
{
|
||||
return insert_data( pos, str_data.c_str(), (Elf_Word)str_data.size() );
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the size of the stream.
|
||||
* @return Size of the stream.
|
||||
*/
|
||||
size_t get_stream_size() const override { return stream_size; }
|
||||
|
||||
/**
|
||||
* @brief Set the size of the stream.
|
||||
* @param value Size of the stream.
|
||||
*/
|
||||
void set_stream_size( size_t value ) override { stream_size = value; }
|
||||
|
||||
protected:
|
||||
ELFIO_GET_SET_ACCESS( Elf64_Off, offset, header.sh_offset );
|
||||
|
||||
/**
|
||||
* @brief Set the index of the section.
|
||||
* @param value Index of the section.
|
||||
*/
|
||||
void set_index( const Elf_Half& value ) override { index = value; }
|
||||
|
||||
/**
|
||||
* @brief Check if the section is compressed.
|
||||
* @return True if compressed, false otherwise.
|
||||
*/
|
||||
bool is_compressed() const
|
||||
{
|
||||
return ( ( get_flags() & SHF_RPX_DEFLATE ) ||
|
||||
( get_flags() & SHF_COMPRESSED ) ) &&
|
||||
compression != nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Load the section from a stream.
|
||||
* @param stream Input stream.
|
||||
* @param header_offset Offset of the header.
|
||||
* @param is_lazy_ Whether to load lazily.
|
||||
* @return True if successful, false otherwise.
|
||||
*/
|
||||
bool load( std::istream& stream,
|
||||
std::streampos header_offset,
|
||||
bool is_lazy_ ) override
|
||||
{
|
||||
pstream = &stream;
|
||||
is_lazy = is_lazy_;
|
||||
|
||||
if ( translator->empty() ) {
|
||||
stream.seekg( 0, std::istream::end );
|
||||
set_stream_size( size_t( stream.tellg() ) );
|
||||
}
|
||||
else {
|
||||
set_stream_size( std::numeric_limits<size_t>::max() );
|
||||
}
|
||||
|
||||
stream.seekg( ( *translator )[header_offset] );
|
||||
stream.read( reinterpret_cast<char*>( &header ), sizeof( header ) );
|
||||
|
||||
if ( !( is_lazy || is_loaded ) ) {
|
||||
bool ret = get_data();
|
||||
|
||||
if ( is_compressed() ) {
|
||||
Elf_Xword size = get_size();
|
||||
Elf_Xword uncompressed_size = 0;
|
||||
auto decompressed_data = compression->inflate(
|
||||
data.get(), convertor, size, uncompressed_size );
|
||||
if ( decompressed_data != nullptr ) {
|
||||
set_size( uncompressed_size );
|
||||
data = std::move( decompressed_data );
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Load the data of the section.
|
||||
* @return True if successful, false otherwise.
|
||||
*/
|
||||
bool load_data() const
|
||||
{
|
||||
Elf_Xword sh_offset =
|
||||
( *translator )[( *convertor )( header.sh_offset )];
|
||||
Elf_Xword size = get_size();
|
||||
|
||||
// Check for integer overflow in offset calculation
|
||||
if ( sh_offset > get_stream_size() ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for integer overflow in size calculation
|
||||
if ( size > get_stream_size() ||
|
||||
size > ( get_stream_size() - sh_offset ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if we need to load data
|
||||
if ( nullptr == data && SHT_NULL != get_type() &&
|
||||
SHT_NOBITS != get_type() ) {
|
||||
// Check if size can be safely converted to size_t
|
||||
if ( size > std::numeric_limits<size_t>::max() - 1 ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
data.reset( new ( std::nothrow ) char[size_t( size ) + 1] );
|
||||
|
||||
if ( ( 0 != size ) && ( nullptr != data ) ) {
|
||||
pstream->seekg( sh_offset );
|
||||
pstream->read( data.get(), size );
|
||||
if ( static_cast<Elf_Xword>( pstream->gcount() ) != size ) {
|
||||
data.reset( nullptr );
|
||||
data_size = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
data_size = size;
|
||||
data.get()[size] = 0; // Safe now as we allocated size + 1
|
||||
}
|
||||
else {
|
||||
data_size = 0;
|
||||
if ( size != 0 ) {
|
||||
return false; // Failed to allocate required memory
|
||||
}
|
||||
}
|
||||
|
||||
is_loaded = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Data already loaded or doesn't need loading
|
||||
is_loaded = ( nullptr != data ) || ( SHT_NULL == get_type() ) ||
|
||||
( SHT_NOBITS == get_type() );
|
||||
return is_loaded;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Save the section to a stream.
|
||||
* @param stream Output stream.
|
||||
* @param header_offset Offset of the header.
|
||||
* @param data_offset Offset of the data.
|
||||
*/
|
||||
void save( std::ostream& stream,
|
||||
std::streampos header_offset,
|
||||
std::streampos data_offset ) override
|
||||
{
|
||||
if ( 0 != get_index() ) {
|
||||
header.sh_offset = decltype( header.sh_offset )( data_offset );
|
||||
header.sh_offset = ( *convertor )( header.sh_offset );
|
||||
}
|
||||
|
||||
save_header( stream, header_offset );
|
||||
if ( get_type() != SHT_NOBITS && get_type() != SHT_NULL &&
|
||||
get_size() != 0 && data != nullptr ) {
|
||||
save_data( stream, data_offset );
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Save the header of the section to a stream.
|
||||
* @param stream Output stream.
|
||||
* @param header_offset Offset of the header.
|
||||
*/
|
||||
void save_header( std::ostream& stream, std::streampos header_offset ) const
|
||||
{
|
||||
adjust_stream_size( stream, header_offset );
|
||||
stream.write( reinterpret_cast<const char*>( &header ),
|
||||
sizeof( header ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Save the data of the section to a stream.
|
||||
* @param stream Output stream.
|
||||
* @param data_offset Offset of the data.
|
||||
*/
|
||||
void save_data( std::ostream& stream, std::streampos data_offset )
|
||||
{
|
||||
adjust_stream_size( stream, data_offset );
|
||||
|
||||
if ( ( ( get_flags() & SHF_COMPRESSED ) ||
|
||||
( get_flags() & SHF_RPX_DEFLATE ) ) &&
|
||||
compression != nullptr ) {
|
||||
Elf_Xword decompressed_size = get_size();
|
||||
Elf_Xword compressed_size = 0;
|
||||
auto compressed_ptr = compression->deflate(
|
||||
data.get(), convertor, decompressed_size, compressed_size );
|
||||
stream.write( compressed_ptr.get(), compressed_size );
|
||||
}
|
||||
else {
|
||||
stream.write( get_data(), get_size() );
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::istream* pstream =
|
||||
nullptr; /**< Pointer to the input stream. */
|
||||
T header = {}; /**< Section header. */
|
||||
Elf_Half index = 0; /**< Index of the section. */
|
||||
std::string name; /**< Name of the section. */
|
||||
mutable std::unique_ptr<char[]> data; /**< Pointer to the data. */
|
||||
mutable Elf_Xword data_size = 0; /**< Size of the data. */
|
||||
std::shared_ptr<endianness_convertor> convertor =
|
||||
nullptr; /**< Pointer to the endianness convertor. */
|
||||
std::shared_ptr<address_translator> translator =
|
||||
nullptr; /**< Pointer to the address translator. */
|
||||
std::shared_ptr<compression_interface> compression =
|
||||
nullptr; /**< Shared pointer to the compression interface. */
|
||||
bool is_address_set = false; /**< Flag indicating if the address is set. */
|
||||
size_t stream_size = 0; /**< Size of the stream. */
|
||||
mutable bool is_lazy =
|
||||
false; /**< Flag indicating if lazy loading is enabled. */
|
||||
mutable bool is_loaded =
|
||||
false; /**< Flag indicating if the data is loaded. */
|
||||
mutable bool can_be_loaded =
|
||||
true; /**< Flag indicating if the data can loaded. This is not the case if the section is corrupted. */
|
||||
};
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_SECTION_HPP
|
||||
405
vybuild/elfio/elfio_segment.hpp
Normal file
405
vybuild/elfio/elfio_segment.hpp
Normal file
@@ -0,0 +1,405 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_SEGMENT_HPP
|
||||
#define ELFIO_SEGMENT_HPP
|
||||
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <new>
|
||||
#include <limits>
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class segment
|
||||
//! \brief Class for accessing segment data
|
||||
class segment
|
||||
{
|
||||
friend class elfio;
|
||||
|
||||
public:
|
||||
virtual ~segment() = default;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the index of the segment
|
||||
//! \return Index of the segment
|
||||
ELFIO_GET_ACCESS_DECL( Elf_Half, index );
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the type of the segment
|
||||
//! \return Type of the segment
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, type );
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the flags of the segment
|
||||
//! \return Flags of the segment
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Word, flags );
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the alignment of the segment
|
||||
//! \return Alignment of the segment
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, align );
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the virtual address of the segment
|
||||
//! \return Virtual address of the segment
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, virtual_address );
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the physical address of the segment
|
||||
//! \return Physical address of the segment
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf64_Addr, physical_address );
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the file size of the segment
|
||||
//! \return File size of the segment
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, file_size );
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the memory size of the segment
|
||||
//! \return Memory size of the segment
|
||||
ELFIO_GET_SET_ACCESS_DECL( Elf_Xword, memory_size );
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the offset of the segment
|
||||
//! \return Offset of the segment
|
||||
ELFIO_GET_ACCESS_DECL( Elf64_Off, offset );
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the data of the segment
|
||||
//! \return Pointer to the data
|
||||
virtual const char* get_data() const = 0;
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Free the data of the segment
|
||||
virtual void free_data() const = 0;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add a section to the segment
|
||||
//! \param psec Pointer to the section
|
||||
//! \param addr_align Alignment of the section
|
||||
//! \return Index of the added section
|
||||
virtual Elf_Half add_section( section* psec, Elf_Xword addr_align ) = 0;
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add a section index to the segment
|
||||
//! \param index Index of the section
|
||||
//! \param addr_align Alignment of the section
|
||||
//! \return Index of the added section
|
||||
virtual Elf_Half add_section_index( Elf_Half index,
|
||||
Elf_Xword addr_align ) = 0;
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the number of sections in the segment
|
||||
//! \return Number of sections in the segment
|
||||
virtual Elf_Half get_sections_num() const = 0;
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the index of a section at a given position
|
||||
//! \param num Position of the section
|
||||
//! \return Index of the section
|
||||
virtual Elf_Half get_section_index_at( Elf_Half num ) const = 0;
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Check if the offset is initialized
|
||||
//! \return True if the offset is initialized, false otherwise
|
||||
virtual bool is_offset_initialized() const = 0;
|
||||
|
||||
protected:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Set the offset of the segment
|
||||
//! \param offset Offset of the segment
|
||||
ELFIO_SET_ACCESS_DECL( Elf64_Off, offset );
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Set the index of the segment
|
||||
//! \param index Index of the segment
|
||||
ELFIO_SET_ACCESS_DECL( Elf_Half, index );
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the sections of the segment
|
||||
//! \return Vector of section indices
|
||||
virtual const std::vector<Elf_Half>& get_sections() const = 0;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Load the segment from a stream
|
||||
//! \param stream Input stream
|
||||
//! \param header_offset Offset of the segment header
|
||||
//! \param is_lazy Whether to load the segment lazily
|
||||
//! \return True if successful, false otherwise
|
||||
virtual bool load( std::istream& stream,
|
||||
std::streampos header_offset,
|
||||
bool is_lazy ) = 0;
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Save the segment to a stream
|
||||
//! \param stream Output stream
|
||||
//! \param header_offset Offset of the segment header
|
||||
//! \param data_offset Offset of the segment data
|
||||
virtual void save( std::ostream& stream,
|
||||
std::streampos header_offset,
|
||||
std::streampos data_offset ) = 0;
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class segment_impl
|
||||
//! \brief Implementation of the segment class
|
||||
template <class T> class segment_impl : public segment
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Constructor
|
||||
//! \param convertor Pointer to the endianness convertor
|
||||
//! \param translator Pointer to the address translator
|
||||
segment_impl( std::shared_ptr<endianness_convertor> convertor,
|
||||
std::shared_ptr<address_translator> translator )
|
||||
: convertor( convertor ), translator( translator )
|
||||
{
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Section info functions
|
||||
ELFIO_GET_SET_ACCESS( Elf_Word, type, ph.p_type );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Word, flags, ph.p_flags );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Xword, align, ph.p_align );
|
||||
ELFIO_GET_SET_ACCESS( Elf64_Addr, virtual_address, ph.p_vaddr );
|
||||
ELFIO_GET_SET_ACCESS( Elf64_Addr, physical_address, ph.p_paddr );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Xword, file_size, ph.p_filesz );
|
||||
ELFIO_GET_SET_ACCESS( Elf_Xword, memory_size, ph.p_memsz );
|
||||
ELFIO_GET_ACCESS( Elf64_Off, offset, ph.p_offset );
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the index of the segment
|
||||
//! \return Index of the segment
|
||||
Elf_Half get_index() const override { return index; }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the data of the segment
|
||||
//! \return Pointer to the data
|
||||
const char* get_data() const override
|
||||
{
|
||||
if ( !is_loaded ) {
|
||||
load_data();
|
||||
}
|
||||
return data.get();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Free the data of the segment
|
||||
void free_data() const override
|
||||
{
|
||||
if ( is_lazy ) {
|
||||
data.reset( nullptr );
|
||||
is_loaded = false;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add a section index to the segment
|
||||
//! \param sec_index Index of the section
|
||||
//! \param addr_align Alignment of the section
|
||||
//! \return Index of the added section
|
||||
Elf_Half add_section_index( Elf_Half sec_index,
|
||||
Elf_Xword addr_align ) override
|
||||
{
|
||||
sections.emplace_back( sec_index );
|
||||
if ( addr_align > get_align() ) {
|
||||
set_align( addr_align );
|
||||
}
|
||||
|
||||
return (Elf_Half)sections.size();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add a section to the segment
|
||||
//! \param psec Pointer to the section
|
||||
//! \param addr_align Alignment of the section
|
||||
//! \return Index of the added section
|
||||
Elf_Half add_section( section* psec, Elf_Xword addr_align ) override
|
||||
{
|
||||
return add_section_index( psec->get_index(), addr_align );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the number of sections in the segment
|
||||
//! \return Number of sections in the segment
|
||||
Elf_Half get_sections_num() const override
|
||||
{
|
||||
return (Elf_Half)sections.size();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the index of a section at a given position
|
||||
//! \param num Position of the section
|
||||
//! \return Index of the section
|
||||
Elf_Half get_section_index_at( Elf_Half num ) const override
|
||||
{
|
||||
if ( num < sections.size() ) {
|
||||
return sections[num];
|
||||
}
|
||||
|
||||
return Elf_Half( -1 );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
protected:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Set the offset of the segment
|
||||
//! \param value Offset of the segment
|
||||
void set_offset( const Elf64_Off& value ) override
|
||||
{
|
||||
ph.p_offset = decltype( ph.p_offset )( value );
|
||||
ph.p_offset = ( *convertor )( ph.p_offset );
|
||||
is_offset_set = true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Check if the offset is initialized
|
||||
//! \return True if the offset is initialized, false otherwise
|
||||
bool is_offset_initialized() const override { return is_offset_set; }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the sections of the segment
|
||||
//! \return Vector of section indices
|
||||
const std::vector<Elf_Half>& get_sections() const override
|
||||
{
|
||||
return sections;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Set the index of the segment
|
||||
//! \param value Index of the segment
|
||||
void set_index( const Elf_Half& value ) override { index = value; }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Load the segment from a stream
|
||||
//! \param stream Input stream
|
||||
//! \param header_offset Offset of the segment header
|
||||
//! \param is_lazy_ Whether to load the segment lazily
|
||||
//! \return True if successful, false otherwise
|
||||
bool load( std::istream& stream,
|
||||
std::streampos header_offset,
|
||||
bool is_lazy_ ) override
|
||||
{
|
||||
pstream = &stream;
|
||||
is_lazy = is_lazy_;
|
||||
|
||||
if ( translator->empty() ) {
|
||||
stream.seekg( 0, std::istream::end );
|
||||
set_stream_size( size_t( stream.tellg() ) );
|
||||
}
|
||||
else {
|
||||
set_stream_size( std::numeric_limits<size_t>::max() );
|
||||
}
|
||||
|
||||
stream.seekg( ( *translator )[header_offset] );
|
||||
stream.read( reinterpret_cast<char*>( &ph ), sizeof( ph ) );
|
||||
|
||||
is_offset_set = true;
|
||||
|
||||
if ( !( is_lazy || is_loaded ) ) {
|
||||
return load_data();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Load the data of the segment
|
||||
//! \return True if successful, false otherwise
|
||||
bool load_data() const
|
||||
{
|
||||
if ( PT_NULL == get_type() || 0 == get_file_size() ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Elf_Xword p_offset = ( *translator )[( *convertor )( ph.p_offset )];
|
||||
Elf_Xword size = get_file_size();
|
||||
|
||||
// Check for integer overflow in offset calculation
|
||||
if ( p_offset > get_stream_size() ) {
|
||||
data = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for integer overflow in size calculation
|
||||
if ( size > get_stream_size() ||
|
||||
size > ( get_stream_size() - p_offset ) ) {
|
||||
data = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if size can be safely converted to size_t
|
||||
if ( size > std::numeric_limits<size_t>::max() - 1 ) {
|
||||
data = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
data.reset( new ( std::nothrow ) char[(size_t)size + 1] );
|
||||
|
||||
pstream->seekg( p_offset );
|
||||
if ( nullptr != data.get() && pstream->read( data.get(), size ) ) {
|
||||
data.get()[size] = 0;
|
||||
}
|
||||
else {
|
||||
data = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
is_loaded = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Save the segment to a stream
|
||||
//! \param stream Output stream
|
||||
//! \param header_offset Offset of the segment header
|
||||
//! \param data_offset Offset of the segment data
|
||||
void save( std::ostream& stream,
|
||||
std::streampos header_offset,
|
||||
std::streampos data_offset ) override
|
||||
{
|
||||
ph.p_offset = decltype( ph.p_offset )( data_offset );
|
||||
ph.p_offset = ( *convertor )( ph.p_offset );
|
||||
adjust_stream_size( stream, header_offset );
|
||||
stream.write( reinterpret_cast<const char*>( &ph ), sizeof( ph ) );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the stream size
|
||||
//! \return Stream size
|
||||
size_t get_stream_size() const { return stream_size; }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Set the stream size
|
||||
//! \param value Stream size
|
||||
void set_stream_size( size_t value ) { stream_size = value; }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
mutable std::istream* pstream = nullptr; //!< Pointer to the input stream
|
||||
T ph = {}; //!< Segment header
|
||||
Elf_Half index = 0; //!< Index of the segment
|
||||
mutable std::unique_ptr<char[]> data; //!< Pointer to the segment data
|
||||
std::vector<Elf_Half> sections; //!< Vector of section indices
|
||||
std::shared_ptr<endianness_convertor> convertor =
|
||||
nullptr; //!< Pointer to the endianness convertor
|
||||
std::shared_ptr<address_translator> translator =
|
||||
nullptr; //!< Pointer to the address translator
|
||||
size_t stream_size = 0; //!< Stream size
|
||||
bool is_offset_set = false; //!< Flag indicating if the offset is set
|
||||
mutable bool is_lazy =
|
||||
false; //!< Flag indicating if the segment is loaded lazily
|
||||
mutable bool is_loaded =
|
||||
false; //!< Flag indicating if the segment is loaded
|
||||
};
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_SEGMENT_HPP
|
||||
143
vybuild/elfio/elfio_strings.hpp
Normal file
143
vybuild/elfio/elfio_strings.hpp
Normal file
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_STRINGS_HPP
|
||||
#define ELFIO_STRINGS_HPP
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <limits>
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class string_section_accessor_template
|
||||
//! \brief Class for accessing string section data
|
||||
template <class S> class string_section_accessor_template
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Constructor
|
||||
//! \param section Pointer to the section
|
||||
explicit string_section_accessor_template( S* section )
|
||||
: string_section( section )
|
||||
{
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get a string from the section
|
||||
//! \param index Index of the string
|
||||
//! \return Pointer to the string, or nullptr if not found
|
||||
const char* get_string( Elf_Word index ) const
|
||||
{
|
||||
if ( string_section ) {
|
||||
const char* data = string_section->get_data();
|
||||
size_t section_size =
|
||||
static_cast<size_t>( string_section->get_size() );
|
||||
|
||||
// Check if index is within bounds
|
||||
if ( index >= section_size || nullptr == data ) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Check for integer overflow in size calculation
|
||||
size_t remaining_size = section_size - index;
|
||||
if ( remaining_size > section_size ) { // Check for underflow
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Use standard C++ functions to find string length
|
||||
const char* str = data + index;
|
||||
const char* end =
|
||||
(const char*)std::memchr( str, '\0', remaining_size );
|
||||
if ( end != nullptr && end < str + remaining_size ) {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add a string to the section
|
||||
//! \param str Pointer to the string
|
||||
//! \return Index of the added string
|
||||
Elf_Word add_string( const char* str )
|
||||
{
|
||||
if ( !str ) {
|
||||
return 0; // Return index of empty string for null input
|
||||
}
|
||||
|
||||
Elf_Word current_position = 0;
|
||||
|
||||
if ( string_section ) {
|
||||
// Strings are added to the end of the current section data
|
||||
current_position =
|
||||
static_cast<Elf_Word>( string_section->get_size() );
|
||||
|
||||
if ( current_position == 0 ) {
|
||||
char empty_string = '\0';
|
||||
string_section->append_data( &empty_string, 1 );
|
||||
current_position++;
|
||||
}
|
||||
|
||||
// Calculate string length and check for overflow
|
||||
size_t str_len = std::strlen( str );
|
||||
if ( str_len > std::numeric_limits<Elf_Word>::max() - 1 ) {
|
||||
return 0; // String too long
|
||||
}
|
||||
|
||||
// Check if appending would overflow section size
|
||||
Elf_Word append_size = static_cast<Elf_Word>( str_len + 1 );
|
||||
if ( append_size >
|
||||
std::numeric_limits<Elf_Word>::max() - current_position ) {
|
||||
return 0; // Would overflow section size
|
||||
}
|
||||
|
||||
string_section->append_data( str, append_size );
|
||||
}
|
||||
|
||||
return current_position;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add a string to the section
|
||||
//! \param str The string to add
|
||||
//! \return Index of the added string
|
||||
Elf_Word add_string( const std::string& str )
|
||||
{
|
||||
return add_string( str.c_str() );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
S* string_section; //!< Pointer to the section
|
||||
};
|
||||
|
||||
using string_section_accessor = string_section_accessor_template<section>;
|
||||
using const_string_section_accessor =
|
||||
string_section_accessor_template<const section>;
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_STRINGS_HPP
|
||||
716
vybuild/elfio/elfio_symbols.hpp
Normal file
716
vybuild/elfio/elfio_symbols.hpp
Normal file
@@ -0,0 +1,716 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_SYMBOLS_HPP
|
||||
#define ELFIO_SYMBOLS_HPP
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @class symbol_section_accessor_template
|
||||
// @brief A template class for accessing symbol sections in an ELF file.
|
||||
//------------------------------------------------------------------------------
|
||||
template <class S> class symbol_section_accessor_template
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Constructor
|
||||
// @param elf_file Reference to the ELF file
|
||||
// @param symbol_section Pointer to the symbol section
|
||||
//------------------------------------------------------------------------------
|
||||
explicit symbol_section_accessor_template( const elfio& elf_file,
|
||||
S* symbol_section )
|
||||
: elf_file( elf_file ), symbol_section( symbol_section )
|
||||
{
|
||||
find_hash_section();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Get the number of symbols in the section
|
||||
// @return Number of symbols
|
||||
//------------------------------------------------------------------------------
|
||||
Elf_Xword get_symbols_num() const
|
||||
{
|
||||
Elf_Xword nRet = 0;
|
||||
|
||||
size_t minimum_symbol_size;
|
||||
switch ( elf_file.get_class() ) {
|
||||
case ELFCLASS32:
|
||||
minimum_symbol_size = sizeof( Elf32_Sym );
|
||||
break;
|
||||
case ELFCLASS64:
|
||||
minimum_symbol_size = sizeof( Elf64_Sym );
|
||||
break;
|
||||
default:
|
||||
return nRet;
|
||||
}
|
||||
|
||||
if ( symbol_section->get_entry_size() >= minimum_symbol_size &&
|
||||
symbol_section->get_size() <= symbol_section->get_stream_size() ) {
|
||||
nRet =
|
||||
symbol_section->get_size() / symbol_section->get_entry_size();
|
||||
}
|
||||
|
||||
return nRet;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Get the symbol at the specified index
|
||||
// @param index Index of the symbol
|
||||
// @param name Name of the symbol
|
||||
// @param value Value of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param bind Binding of the symbol
|
||||
// @param type Type of the symbol
|
||||
// @param section_index Section index of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @return True if the symbol is found, false otherwise
|
||||
//------------------------------------------------------------------------------
|
||||
bool get_symbol( Elf_Xword index,
|
||||
std::string& name,
|
||||
Elf64_Addr& value,
|
||||
Elf_Xword& size,
|
||||
unsigned char& bind,
|
||||
unsigned char& type,
|
||||
Elf_Half& section_index,
|
||||
unsigned char& other ) const
|
||||
{
|
||||
bool ret = false;
|
||||
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
ret = generic_get_symbol<Elf32_Sym>( index, name, value, size, bind,
|
||||
type, section_index, other );
|
||||
}
|
||||
else {
|
||||
ret = generic_get_symbol<Elf64_Sym>( index, name, value, size, bind,
|
||||
type, section_index, other );
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Get the symbol with the specified name
|
||||
// @param name Name of the symbol
|
||||
// @param value Value of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param bind Binding of the symbol
|
||||
// @param type Type of the symbol
|
||||
// @param section_index Section index of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @return True if the symbol is found, false otherwise
|
||||
//------------------------------------------------------------------------------
|
||||
bool get_symbol( const std::string& name,
|
||||
Elf64_Addr& value,
|
||||
Elf_Xword& size,
|
||||
unsigned char& bind,
|
||||
unsigned char& type,
|
||||
Elf_Half& section_index,
|
||||
unsigned char& other ) const
|
||||
{
|
||||
bool ret = false;
|
||||
|
||||
if ( 0 != get_hash_table_index() ) {
|
||||
if ( hash_section->get_type() == SHT_HASH ) {
|
||||
ret = hash_lookup( name, value, size, bind, type, section_index,
|
||||
other );
|
||||
}
|
||||
if ( hash_section->get_type() == SHT_GNU_HASH ||
|
||||
hash_section->get_type() == DT_GNU_HASH ) {
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
ret = gnu_hash_lookup<std::uint32_t>(
|
||||
name, value, size, bind, type, section_index, other );
|
||||
}
|
||||
else {
|
||||
ret = gnu_hash_lookup<std::uint64_t>(
|
||||
name, value, size, bind, type, section_index, other );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( !ret ) {
|
||||
for ( Elf_Xword i = 0; !ret && i < get_symbols_num(); i++ ) {
|
||||
std::string symbol_name;
|
||||
if ( get_symbol( i, symbol_name, value, size, bind, type,
|
||||
section_index, other ) &&
|
||||
( symbol_name == name ) ) {
|
||||
ret = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Get the symbol with the specified value
|
||||
// @param value Value of the symbol
|
||||
// @param name Name of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param bind Binding of the symbol
|
||||
// @param type Type of the symbol
|
||||
// @param section_index Section index of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @return True if the symbol is found, false otherwise
|
||||
//------------------------------------------------------------------------------
|
||||
bool get_symbol( const Elf64_Addr& value,
|
||||
std::string& name,
|
||||
Elf_Xword& size,
|
||||
unsigned char& bind,
|
||||
unsigned char& type,
|
||||
Elf_Half& section_index,
|
||||
unsigned char& other ) const
|
||||
{
|
||||
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
Elf_Xword idx = 0;
|
||||
bool match = false;
|
||||
Elf64_Addr v = 0;
|
||||
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
match = generic_search_symbols<Elf32_Sym>(
|
||||
[&]( const Elf32_Sym* sym ) {
|
||||
return ( *convertor )( sym->st_value ) == value;
|
||||
},
|
||||
idx );
|
||||
}
|
||||
else {
|
||||
match = generic_search_symbols<Elf64_Sym>(
|
||||
[&]( const Elf64_Sym* sym ) {
|
||||
return ( *convertor )( sym->st_value ) == value;
|
||||
},
|
||||
idx );
|
||||
}
|
||||
|
||||
if ( match ) {
|
||||
return get_symbol( idx, name, v, size, bind, type, section_index,
|
||||
other );
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Add a symbol to the section
|
||||
// @param name Name of the symbol
|
||||
// @param value Value of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param info Info of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @param shndx Section index of the symbol
|
||||
// @return Index of the added symbol
|
||||
//------------------------------------------------------------------------------
|
||||
Elf_Word add_symbol( Elf_Word name,
|
||||
Elf64_Addr value,
|
||||
Elf_Xword size,
|
||||
unsigned char info,
|
||||
unsigned char other,
|
||||
Elf_Half shndx )
|
||||
{
|
||||
Elf_Word nRet;
|
||||
|
||||
if ( symbol_section->get_size() == 0 ) {
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
nRet = generic_add_symbol<Elf32_Sym>( 0, 0, 0, 0, 0, 0 );
|
||||
}
|
||||
else {
|
||||
nRet = generic_add_symbol<Elf64_Sym>( 0, 0, 0, 0, 0, 0 );
|
||||
}
|
||||
}
|
||||
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
nRet = generic_add_symbol<Elf32_Sym>( name, value, size, info,
|
||||
other, shndx );
|
||||
}
|
||||
else {
|
||||
nRet = generic_add_symbol<Elf64_Sym>( name, value, size, info,
|
||||
other, shndx );
|
||||
}
|
||||
|
||||
return nRet;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Add a symbol to the section
|
||||
// @param name Name of the symbol
|
||||
// @param value Value of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param bind Binding of the symbol
|
||||
// @param type Type of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @param shndx Section index of the symbol
|
||||
// @return Index of the added symbol
|
||||
//------------------------------------------------------------------------------
|
||||
Elf_Word add_symbol( Elf_Word name,
|
||||
Elf64_Addr value,
|
||||
Elf_Xword size,
|
||||
unsigned char bind,
|
||||
unsigned char type,
|
||||
unsigned char other,
|
||||
Elf_Half shndx )
|
||||
{
|
||||
return add_symbol( name, value, size, ELF_ST_INFO( bind, type ), other,
|
||||
shndx );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Add a symbol to the section
|
||||
// @param pStrWriter String section accessor
|
||||
// @param str Name of the symbol
|
||||
// @param value Value of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param info Info of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @param shndx Section index of the symbol
|
||||
// @return Index of the added symbol
|
||||
//------------------------------------------------------------------------------
|
||||
Elf_Word add_symbol( string_section_accessor& pStrWriter,
|
||||
const char* str,
|
||||
Elf64_Addr value,
|
||||
Elf_Xword size,
|
||||
unsigned char info,
|
||||
unsigned char other,
|
||||
Elf_Half shndx )
|
||||
{
|
||||
Elf_Word index = pStrWriter.add_string( str );
|
||||
return add_symbol( index, value, size, info, other, shndx );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Add a symbol to the section
|
||||
// @param pStrWriter String section accessor
|
||||
// @param str Name of the symbol
|
||||
// @param value Value of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param bind Binding of the symbol
|
||||
// @param type Type of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @param shndx Section index of the symbol
|
||||
// @return Index of the added symbol
|
||||
//------------------------------------------------------------------------------
|
||||
Elf_Word add_symbol( string_section_accessor& pStrWriter,
|
||||
const char* str,
|
||||
Elf64_Addr value,
|
||||
Elf_Xword size,
|
||||
unsigned char bind,
|
||||
unsigned char type,
|
||||
unsigned char other,
|
||||
Elf_Half shndx )
|
||||
{
|
||||
return add_symbol( pStrWriter, str, value, size,
|
||||
ELF_ST_INFO( bind, type ), other, shndx );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Arrange local symbols in the section
|
||||
// @param func Function to be called for each pair of symbols
|
||||
// @return Number of local symbols
|
||||
//------------------------------------------------------------------------------
|
||||
Elf_Xword arrange_local_symbols(
|
||||
std::function<void( Elf_Xword first, Elf_Xword second )> func =
|
||||
nullptr )
|
||||
{
|
||||
Elf_Xword nRet = 0;
|
||||
|
||||
if ( elf_file.get_class() == ELFCLASS32 ) {
|
||||
nRet = generic_arrange_local_symbols<Elf32_Sym>( func );
|
||||
}
|
||||
else {
|
||||
nRet = generic_arrange_local_symbols<Elf64_Sym>( func );
|
||||
}
|
||||
|
||||
return nRet;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Find the hash section
|
||||
//------------------------------------------------------------------------------
|
||||
void find_hash_section()
|
||||
{
|
||||
Elf_Half nSecNo = elf_file.sections.size();
|
||||
for ( Elf_Half i = 0; i < nSecNo; ++i ) {
|
||||
const section* sec = elf_file.sections[i];
|
||||
if ( sec->get_link() == symbol_section->get_index() &&
|
||||
( sec->get_type() == SHT_HASH ||
|
||||
sec->get_type() == SHT_GNU_HASH ||
|
||||
sec->get_type() == DT_GNU_HASH ) ) {
|
||||
hash_section = sec;
|
||||
hash_section_index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Get the index of the string table
|
||||
// @return Index of the string table
|
||||
//------------------------------------------------------------------------------
|
||||
Elf_Half get_string_table_index() const
|
||||
{
|
||||
return (Elf_Half)symbol_section->get_link();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Get the index of the hash table
|
||||
// @return Index of the hash table
|
||||
//------------------------------------------------------------------------------
|
||||
Elf_Half get_hash_table_index() const { return hash_section_index; }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Lookup a symbol in the hash table
|
||||
// @param name Name of the symbol
|
||||
// @param value Value of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param bind Binding of the symbol
|
||||
// @param type Type of the symbol
|
||||
// @param section_index Section index of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @return True if the symbol is found, false otherwise
|
||||
//------------------------------------------------------------------------------
|
||||
bool hash_lookup( const std::string& name,
|
||||
Elf64_Addr& value,
|
||||
Elf_Xword& size,
|
||||
unsigned char& bind,
|
||||
unsigned char& type,
|
||||
Elf_Half& section_index,
|
||||
unsigned char& other ) const
|
||||
{
|
||||
bool ret = false;
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
Elf_Word nbucket = *(const Elf_Word*)hash_section->get_data();
|
||||
nbucket = ( *convertor )( nbucket );
|
||||
Elf_Word nchain =
|
||||
*(const Elf_Word*)( hash_section->get_data() + sizeof( Elf_Word ) );
|
||||
nchain = ( *convertor )( nchain );
|
||||
Elf_Word val = elf_hash( (const unsigned char*)name.c_str() );
|
||||
Elf_Word y =
|
||||
*(const Elf_Word*)( hash_section->get_data() +
|
||||
( 2 + val % nbucket ) * sizeof( Elf_Word ) );
|
||||
y = ( *convertor )( y );
|
||||
std::string str;
|
||||
get_symbol( y, str, value, size, bind, type, section_index, other );
|
||||
while ( str != name && STN_UNDEF != y && y < nchain ) {
|
||||
y = *(const Elf_Word*)( hash_section->get_data() +
|
||||
( 2 + nbucket + y ) * sizeof( Elf_Word ) );
|
||||
y = ( *convertor )( y );
|
||||
get_symbol( y, str, value, size, bind, type, section_index, other );
|
||||
}
|
||||
|
||||
if ( str == name ) {
|
||||
ret = true;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Lookup a symbol in the GNU hash table
|
||||
// @param name Name of the symbol
|
||||
// @param value Value of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param bind Binding of the symbol
|
||||
// @param type Type of the symbol
|
||||
// @param section_index Section index of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @return True if the symbol is found, false otherwise
|
||||
//------------------------------------------------------------------------------
|
||||
template <class T>
|
||||
bool gnu_hash_lookup( const std::string& name,
|
||||
Elf64_Addr& value,
|
||||
Elf_Xword& size,
|
||||
unsigned char& bind,
|
||||
unsigned char& type,
|
||||
Elf_Half& section_index,
|
||||
unsigned char& other ) const
|
||||
{
|
||||
bool ret = false;
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
std::uint32_t nbuckets =
|
||||
*( (std::uint32_t*)hash_section->get_data() + 0 );
|
||||
std::uint32_t symoffset =
|
||||
*( (std::uint32_t*)hash_section->get_data() + 1 );
|
||||
std::uint32_t bloom_size =
|
||||
*( (std::uint32_t*)hash_section->get_data() + 2 );
|
||||
std::uint32_t bloom_shift =
|
||||
*( (std::uint32_t*)hash_section->get_data() + 3 );
|
||||
nbuckets = ( *convertor )( nbuckets );
|
||||
symoffset = ( *convertor )( symoffset );
|
||||
bloom_size = ( *convertor )( bloom_size );
|
||||
bloom_shift = ( *convertor )( bloom_shift );
|
||||
|
||||
auto* bloom_filter =
|
||||
(T*)( hash_section->get_data() + 4 * sizeof( std::uint32_t ) );
|
||||
|
||||
std::uint32_t hash = elf_gnu_hash( (const unsigned char*)name.c_str() );
|
||||
std::uint32_t bloom_index = ( hash / ( 8 * sizeof( T ) ) ) % bloom_size;
|
||||
T bloom_bits =
|
||||
( (T)1 << ( hash % ( 8 * sizeof( T ) ) ) ) |
|
||||
( (T)1 << ( ( hash >> bloom_shift ) % ( 8 * sizeof( T ) ) ) );
|
||||
|
||||
if ( ( ( *convertor )( bloom_filter[bloom_index] ) & bloom_bits ) !=
|
||||
bloom_bits )
|
||||
return ret;
|
||||
|
||||
std::uint32_t bucket = hash % nbuckets;
|
||||
auto* buckets = (std::uint32_t*)( hash_section->get_data() +
|
||||
4 * sizeof( std::uint32_t ) +
|
||||
bloom_size * sizeof( T ) );
|
||||
auto* chains = (std::uint32_t*)( hash_section->get_data() +
|
||||
4 * sizeof( std::uint32_t ) +
|
||||
bloom_size * sizeof( T ) +
|
||||
nbuckets * sizeof( std::uint32_t ) );
|
||||
|
||||
if ( ( *convertor )( buckets[bucket] ) >= symoffset ) {
|
||||
std::uint32_t chain_index =
|
||||
( *convertor )( buckets[bucket] ) - symoffset;
|
||||
std::uint32_t chain_hash = ( *convertor )( chains[chain_index] );
|
||||
std::string symname;
|
||||
|
||||
while ( true ) {
|
||||
if ( ( chain_hash >> 1 ) == ( hash >> 1 ) &&
|
||||
get_symbol( chain_index + symoffset, symname, value, size,
|
||||
bind, type, section_index, other ) &&
|
||||
( name == symname ) ) {
|
||||
ret = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if ( chain_hash & 1 )
|
||||
break;
|
||||
|
||||
chain_hash = ( *convertor )( chains[++chain_index] );
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Get the symbol at the specified index
|
||||
// @param index Index of the symbol
|
||||
// @return Pointer to the symbol
|
||||
//------------------------------------------------------------------------------
|
||||
template <class T> const T* generic_get_symbol_ptr( Elf_Xword index ) const
|
||||
{
|
||||
if ( 0 != symbol_section->get_data() && index < get_symbols_num() ) {
|
||||
if ( symbol_section->get_entry_size() < sizeof( T ) ) {
|
||||
return nullptr;
|
||||
}
|
||||
const auto* pSym = reinterpret_cast<const T*>(
|
||||
symbol_section->get_data() +
|
||||
index * symbol_section->get_entry_size() );
|
||||
|
||||
return pSym;
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Search for a symbol in the section
|
||||
// @param match Function to be called for each symbol
|
||||
// @param idx Index of the found symbol
|
||||
// @return True if the symbol is found, false otherwise
|
||||
//------------------------------------------------------------------------------
|
||||
template <class T>
|
||||
bool generic_search_symbols( std::function<bool( const T* )> match,
|
||||
Elf_Xword& idx ) const
|
||||
{
|
||||
for ( Elf_Xword i = 0; i < get_symbols_num(); i++ ) {
|
||||
const T* symPtr = generic_get_symbol_ptr<T>( i );
|
||||
|
||||
if ( symPtr == nullptr )
|
||||
return false;
|
||||
|
||||
if ( match( symPtr ) ) {
|
||||
idx = i;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Get the symbol at the specified index
|
||||
// @param index Index of the symbol
|
||||
// @param name Name of the symbol
|
||||
// @param value Value of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param bind Binding of the symbol
|
||||
// @param type Type of the symbol
|
||||
// @param section_index Section index of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @return True if the symbol is found, false otherwise
|
||||
//------------------------------------------------------------------------------
|
||||
template <class T>
|
||||
bool generic_get_symbol( Elf_Xword index,
|
||||
std::string& name,
|
||||
Elf64_Addr& value,
|
||||
Elf_Xword& size,
|
||||
unsigned char& bind,
|
||||
unsigned char& type,
|
||||
Elf_Half& section_index,
|
||||
unsigned char& other ) const
|
||||
{
|
||||
bool ret = false;
|
||||
|
||||
if ( nullptr != symbol_section->get_data() &&
|
||||
index < get_symbols_num() ) {
|
||||
const auto* pSym = reinterpret_cast<const T*>(
|
||||
symbol_section->get_data() +
|
||||
index * symbol_section->get_entry_size() );
|
||||
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
section* string_section =
|
||||
elf_file.sections[get_string_table_index()];
|
||||
string_section_accessor str_reader( string_section );
|
||||
const char* pStr =
|
||||
str_reader.get_string( ( *convertor )( pSym->st_name ) );
|
||||
if ( nullptr != pStr ) {
|
||||
name = pStr;
|
||||
}
|
||||
value = ( *convertor )( pSym->st_value );
|
||||
size = ( *convertor )( pSym->st_size );
|
||||
bind = ELF_ST_BIND( pSym->st_info );
|
||||
type = ELF_ST_TYPE( pSym->st_info );
|
||||
section_index = ( *convertor )( pSym->st_shndx );
|
||||
other = pSym->st_other;
|
||||
|
||||
ret = true;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Add a symbol to the section
|
||||
// @param name Name of the symbol
|
||||
// @param value Value of the symbol
|
||||
// @param size Size of the symbol
|
||||
// @param info Info of the symbol
|
||||
// @param other Other attributes of the symbol
|
||||
// @param shndx Section index of the symbol
|
||||
// @return Index of the added symbol
|
||||
//------------------------------------------------------------------------------
|
||||
template <class T>
|
||||
Elf_Word generic_add_symbol( Elf_Word name,
|
||||
Elf64_Addr value,
|
||||
Elf_Xword size,
|
||||
unsigned char info,
|
||||
unsigned char other,
|
||||
Elf_Half shndx )
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
T entry;
|
||||
entry.st_name = ( *convertor )( name );
|
||||
entry.st_value = decltype( entry.st_value )( value );
|
||||
entry.st_value = ( *convertor )( entry.st_value );
|
||||
entry.st_size = decltype( entry.st_size )( size );
|
||||
entry.st_size = ( *convertor )( entry.st_size );
|
||||
entry.st_info = ( *convertor )( info );
|
||||
entry.st_other = ( *convertor )( other );
|
||||
entry.st_shndx = ( *convertor )( shndx );
|
||||
|
||||
symbol_section->append_data( reinterpret_cast<char*>( &entry ),
|
||||
sizeof( entry ) );
|
||||
|
||||
Elf_Word nRet =
|
||||
Elf_Word( symbol_section->get_size() / sizeof( entry ) - 1 );
|
||||
|
||||
return nRet;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// @brief Arrange local symbols in the section
|
||||
// @param func Function to be called for each pair of symbols
|
||||
// @return Number of local symbols
|
||||
//------------------------------------------------------------------------------
|
||||
template <class T>
|
||||
Elf_Xword generic_arrange_local_symbols(
|
||||
std::function<void( Elf_Xword first, Elf_Xword second )> func )
|
||||
{
|
||||
const auto& convertor = elf_file.get_convertor();
|
||||
|
||||
Elf_Word first_not_local =
|
||||
1; // Skip the first entry. It is always NOTYPE
|
||||
Elf_Xword current = 0;
|
||||
Elf_Xword count = get_symbols_num();
|
||||
|
||||
while ( true ) {
|
||||
T* p1 = nullptr;
|
||||
T* p2 = nullptr;
|
||||
|
||||
while ( first_not_local < count ) {
|
||||
p1 = const_cast<T*>(
|
||||
generic_get_symbol_ptr<T>( first_not_local ) );
|
||||
if ( ELF_ST_BIND( ( *convertor )( p1->st_info ) ) != STB_LOCAL )
|
||||
break;
|
||||
++first_not_local;
|
||||
}
|
||||
|
||||
current = first_not_local + 1;
|
||||
while ( current < count ) {
|
||||
p2 = const_cast<T*>( generic_get_symbol_ptr<T>( current ) );
|
||||
if ( ELF_ST_BIND( ( *convertor )( p2->st_info ) ) == STB_LOCAL )
|
||||
break;
|
||||
++current;
|
||||
}
|
||||
|
||||
if ( first_not_local < count && current < count ) {
|
||||
if ( func )
|
||||
func( first_not_local, current );
|
||||
|
||||
std::swap( *p1, *p2 );
|
||||
}
|
||||
else {
|
||||
// Update 'info' field of the section
|
||||
symbol_section->set_info( first_not_local );
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return first_not_local;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
const elfio& elf_file; ///< Reference to the ELF file
|
||||
S* symbol_section; ///< Pointer to the symbol section
|
||||
Elf_Half hash_section_index{ 0 }; ///< Index of the hash section
|
||||
const section* hash_section{ nullptr }; ///< Pointer to the hash section
|
||||
};
|
||||
|
||||
using symbol_section_accessor = symbol_section_accessor_template<section>;
|
||||
using const_symbol_section_accessor =
|
||||
symbol_section_accessor_template<const section>;
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_SYMBOLS_HPP
|
||||
373
vybuild/elfio/elfio_utils.hpp
Normal file
373
vybuild/elfio/elfio_utils.hpp
Normal file
@@ -0,0 +1,373 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_UTILS_HPP
|
||||
#define ELFIO_UTILS_HPP
|
||||
|
||||
#include <cstdint>
|
||||
#include <ostream>
|
||||
#include <cstring>
|
||||
|
||||
#define ELFIO_GET_ACCESS_DECL( TYPE, NAME ) virtual TYPE get_##NAME() const = 0
|
||||
|
||||
#define ELFIO_SET_ACCESS_DECL( TYPE, NAME ) \
|
||||
virtual void set_##NAME( const TYPE& value ) = 0
|
||||
|
||||
#define ELFIO_GET_SET_ACCESS_DECL( TYPE, NAME ) \
|
||||
virtual TYPE get_##NAME() const = 0; \
|
||||
virtual void set_##NAME( const TYPE& value ) = 0
|
||||
|
||||
#define ELFIO_GET_ACCESS( TYPE, NAME, FIELD ) \
|
||||
TYPE get_##NAME() const override { return ( *convertor )( FIELD ); }
|
||||
|
||||
#define ELFIO_SET_ACCESS( TYPE, NAME, FIELD ) \
|
||||
void set_##NAME( const TYPE& value ) override \
|
||||
{ \
|
||||
FIELD = decltype( FIELD )( value ); \
|
||||
FIELD = ( *convertor )( FIELD ); \
|
||||
}
|
||||
#define ELFIO_GET_SET_ACCESS( TYPE, NAME, FIELD ) \
|
||||
TYPE get_##NAME() const override { return ( *convertor )( FIELD ); } \
|
||||
void set_##NAME( const TYPE& value ) override \
|
||||
{ \
|
||||
FIELD = decltype( FIELD )( value ); \
|
||||
FIELD = ( *convertor )( FIELD ); \
|
||||
}
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class endianness_convertor
|
||||
//! \brief Class for converting endianness of data
|
||||
class endianness_convertor
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Setup the endianness convertor
|
||||
//! \param elf_file_encoding The encoding of the ELF file
|
||||
void setup( unsigned char elf_file_encoding )
|
||||
{
|
||||
need_conversion = ( elf_file_encoding != get_host_encoding() );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Convert a 64-bit unsigned integer
|
||||
//! \param value The value to convert
|
||||
//! \return The converted value
|
||||
std::uint64_t operator()( std::uint64_t value ) const
|
||||
{
|
||||
if ( !need_conversion ) {
|
||||
return value;
|
||||
}
|
||||
value = ( ( value & 0x00000000000000FFuLL ) << 56 ) |
|
||||
( ( value & 0x000000000000FF00uLL ) << 40 ) |
|
||||
( ( value & 0x0000000000FF0000uLL ) << 24 ) |
|
||||
( ( value & 0x00000000FF000000uLL ) << 8 ) |
|
||||
( ( value & 0x000000FF00000000uLL ) >> 8 ) |
|
||||
( ( value & 0x0000FF0000000000uLL ) >> 24 ) |
|
||||
( ( value & 0x00FF000000000000uLL ) >> 40 ) |
|
||||
( ( value & 0xFF00000000000000uLL ) >> 56 );
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Convert a 64-bit signed integer
|
||||
//! \param value The value to convert
|
||||
//! \return The converted value
|
||||
std::int64_t operator()( std::int64_t value ) const
|
||||
{
|
||||
if ( !need_conversion ) {
|
||||
return value;
|
||||
}
|
||||
return ( std::int64_t )( *this )( (std::uint64_t)value );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Convert a 32-bit unsigned integer
|
||||
//! \param value The value to convert
|
||||
//! \return The converted value
|
||||
std::uint32_t operator()( std::uint32_t value ) const
|
||||
{
|
||||
if ( !need_conversion ) {
|
||||
return value;
|
||||
}
|
||||
value =
|
||||
( ( value & 0x000000FF ) << 24 ) | ( ( value & 0x0000FF00 ) << 8 ) |
|
||||
( ( value & 0x00FF0000 ) >> 8 ) | ( ( value & 0xFF000000 ) >> 24 );
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Convert a 32-bit signed integer
|
||||
//! \param value The value to convert
|
||||
//! \return The converted value
|
||||
std::int32_t operator()( std::int32_t value ) const
|
||||
{
|
||||
if ( !need_conversion ) {
|
||||
return value;
|
||||
}
|
||||
return ( std::int32_t )( *this )( (std::uint32_t)value );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Convert a 16-bit unsigned integer
|
||||
//! \param value The value to convert
|
||||
//! \return The converted value
|
||||
std::uint16_t operator()( std::uint16_t value ) const
|
||||
{
|
||||
if ( !need_conversion ) {
|
||||
return value;
|
||||
}
|
||||
value = ( std::uint16_t )( ( value & 0x00FF ) << 8 ) |
|
||||
( ( value & 0xFF00 ) >> 8 );
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Convert a 16-bit signed integer
|
||||
//! \param value The value to convert
|
||||
//! \return The converted value
|
||||
std::int16_t operator()( std::int16_t value ) const
|
||||
{
|
||||
if ( !need_conversion ) {
|
||||
return value;
|
||||
}
|
||||
return ( std::int16_t )( *this )( (std::uint16_t)value );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Convert an 8-bit signed integer
|
||||
//! \param value The value to convert
|
||||
//! \return The converted value
|
||||
std::int8_t operator()( std::int8_t value ) const { return value; }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Convert an 8-bit unsigned integer
|
||||
//! \param value The value to convert
|
||||
//! \return The converted value
|
||||
std::uint8_t operator()( std::uint8_t value ) const { return value; }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the host encoding
|
||||
//! \return The host encoding
|
||||
unsigned char get_host_encoding() const
|
||||
{
|
||||
static const int tmp = 1;
|
||||
if ( 1 == *reinterpret_cast<const char*>( &tmp ) ) {
|
||||
return ELFDATA2LSB;
|
||||
}
|
||||
else {
|
||||
return ELFDATA2MSB;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
bool need_conversion = false; //!< Flag indicating if conversion is needed
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \struct address_translation
|
||||
//! \brief Structure for address translation
|
||||
struct address_translation
|
||||
{
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Constructor
|
||||
//! \param start The start address
|
||||
//! \param size The size of the address range
|
||||
//! \param mapped_to The mapped address
|
||||
address_translation( std::uint64_t start,
|
||||
std::uint64_t size,
|
||||
std::uint64_t mapped_to )
|
||||
: start( start ), size( size ), mapped_to( mapped_to ){};
|
||||
std::streampos start; //!< Start address
|
||||
std::streampos size; //!< Size of the address range
|
||||
std::streampos mapped_to; //!< Mapped address
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class address_translator
|
||||
//! \brief Class for translating addresses
|
||||
class address_translator
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Set address translation
|
||||
//! \param addr_trans Vector of address translations
|
||||
void set_address_translation( std::vector<address_translation>& addr_trans )
|
||||
{
|
||||
addr_translations = addr_trans;
|
||||
|
||||
std::sort( addr_translations.begin(), addr_translations.end(),
|
||||
[]( const address_translation& a,
|
||||
const address_translation& b ) -> bool {
|
||||
return a.start < b.start;
|
||||
} );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Translate an address
|
||||
//! \param value The address to translate
|
||||
//! \return The translated address
|
||||
std::streampos operator[]( std::streampos value ) const
|
||||
{
|
||||
if ( addr_translations.empty() ) {
|
||||
return value;
|
||||
}
|
||||
|
||||
for ( auto& t : addr_translations ) {
|
||||
if ( ( t.start <= value ) && ( ( value - t.start ) < t.size ) ) {
|
||||
return value - t.start + t.mapped_to;
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Check if the address translator is empty
|
||||
//! \return True if empty, false otherwise
|
||||
bool empty() const { return addr_translations.empty(); }
|
||||
|
||||
private:
|
||||
std::vector<address_translation>
|
||||
addr_translations; //!< Vector of address translations
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Calculate the ELF hash of a name
|
||||
//! \param name The name to hash
|
||||
//! \return The ELF hash
|
||||
inline std::uint32_t elf_hash( const unsigned char* name )
|
||||
{
|
||||
std::uint32_t h = 0;
|
||||
std::uint32_t g = 0;
|
||||
while ( *name != '\0' ) {
|
||||
h = ( h << 4 ) + *name++;
|
||||
g = h & 0xf0000000;
|
||||
if ( g != 0 )
|
||||
h ^= g >> 24;
|
||||
h &= ~g;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Calculate the GNU hash of a name
|
||||
//! \param s The name to hash
|
||||
//! \return The GNU hash
|
||||
inline std::uint32_t elf_gnu_hash( const unsigned char* s )
|
||||
{
|
||||
std::uint32_t h = 0x1505;
|
||||
for ( unsigned char c = *s; c != '\0'; c = *++s )
|
||||
h = ( h << 5 ) + h + c;
|
||||
return h;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Convert a value to a hexadecimal string
|
||||
//! \param value The value to convert
|
||||
//! \return The hexadecimal string
|
||||
inline std::string to_hex_string( std::uint64_t value )
|
||||
{
|
||||
std::string str;
|
||||
|
||||
while ( value ) {
|
||||
if ( auto digit = value & 0xF; digit < 0xA ) {
|
||||
str = char( '0' + digit ) + str;
|
||||
}
|
||||
else {
|
||||
str = char( 'A' + digit - 0xA ) + str;
|
||||
}
|
||||
value >>= 4;
|
||||
}
|
||||
|
||||
return "0x" + str;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Adjust the size of a stream
|
||||
//! \param stream The stream to adjust
|
||||
//! \param offset The offset to adjust to
|
||||
inline void adjust_stream_size( std::ostream& stream, std::streamsize offset )
|
||||
{
|
||||
stream.seekp( 0, std::ios_base::end );
|
||||
if ( stream.tellp() < offset ) {
|
||||
std::streamsize size = offset - stream.tellp();
|
||||
stream.write( std::string( size_t( size ), '\0' ).c_str(), size );
|
||||
}
|
||||
stream.seekp( offset );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the length of a string with a maximum length
|
||||
//! \param s The string
|
||||
//! \param n The maximum length
|
||||
//! \return The length of the string
|
||||
inline static size_t strnlength( const char* s, size_t n )
|
||||
{
|
||||
auto found = (const char*)std::memchr( s, '\0', n );
|
||||
return found ? (size_t)( found - s ) : n;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class compression_interface
|
||||
//! \brief Interface for compression and decompression
|
||||
class compression_interface
|
||||
{
|
||||
public:
|
||||
virtual ~compression_interface() = default;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Decompress a compressed section
|
||||
//! \param data The buffer of compressed data
|
||||
//! \param convertor Pointer to an endianness convertor instance
|
||||
//! \param compressed_size The size of the compressed data buffer
|
||||
//! \param uncompressed_size Reference to a variable to store the decompressed buffer size
|
||||
//! \return A smart pointer to the decompressed data
|
||||
virtual std::unique_ptr<char[]>
|
||||
inflate( const char* data,
|
||||
std::shared_ptr<const endianness_convertor> convertor,
|
||||
Elf_Xword compressed_size,
|
||||
Elf_Xword& uncompressed_size ) const = 0;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Compress a section
|
||||
//! \param data The buffer of uncompressed data
|
||||
//! \param convertor Pointer to an endianness convertor instance
|
||||
//! \param decompressed_size The size of the uncompressed data buffer
|
||||
//! \param compressed_size Reference to a variable to store the compressed buffer size
|
||||
//! \return A smart pointer to the compressed data
|
||||
virtual std::unique_ptr<char[]>
|
||||
deflate( const char* data,
|
||||
std::shared_ptr<const endianness_convertor> convertor,
|
||||
Elf_Xword decompressed_size,
|
||||
Elf_Xword& compressed_size ) const = 0;
|
||||
};
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_UTILS_HPP
|
||||
4
vybuild/elfio/elfio_version.hpp
Normal file
4
vybuild/elfio/elfio_version.hpp
Normal file
@@ -0,0 +1,4 @@
|
||||
//------------------------------------------------------------------------------
|
||||
//! \def ELFIO_VERSION
|
||||
//! \brief Defines the version of the ELFIO library
|
||||
#define ELFIO_VERSION "3.14"
|
||||
310
vybuild/elfio/elfio_versym.hpp
Normal file
310
vybuild/elfio/elfio_versym.hpp
Normal file
@@ -0,0 +1,310 @@
|
||||
/*
|
||||
Copyright (C) 2001-present by Serge Lamikhov-Center
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef ELFIO_VERSYM_HPP
|
||||
#define ELFIO_VERSYM_HPP
|
||||
|
||||
namespace ELFIO {
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class versym_section_accessor_template
|
||||
//! \brief Class for accessing version symbol section data
|
||||
template <class S> class versym_section_accessor_template
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Constructor
|
||||
//! \param section Pointer to the section
|
||||
explicit versym_section_accessor_template( S* section )
|
||||
: versym_section( section )
|
||||
{
|
||||
if ( section != nullptr ) {
|
||||
entries_num = decltype( entries_num )( section->get_size() /
|
||||
sizeof( Elf_Half ) );
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the number of entries
|
||||
//! \return Number of entries
|
||||
Elf_Word get_entries_num() const
|
||||
{
|
||||
if ( versym_section ) {
|
||||
return entries_num;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get an entry
|
||||
//! \param no Index of the entry
|
||||
//! \param value Value of the entry
|
||||
//! \return True if successful, false otherwise
|
||||
bool get_entry( Elf_Word no, Elf_Half& value ) const
|
||||
{
|
||||
if ( versym_section && ( no < get_entries_num() ) ) {
|
||||
value = ( (Elf_Half*)versym_section->get_data() )[no];
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Modify an entry
|
||||
//! \param no Index of the entry
|
||||
//! \param value New value of the entry
|
||||
//! \return True if successful, false otherwise
|
||||
bool modify_entry( Elf_Word no, Elf_Half value )
|
||||
{
|
||||
if ( versym_section && ( no < get_entries_num() ) ) {
|
||||
( (Elf_Half*)versym_section->get_data() )[no] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Add an entry
|
||||
//! \param value Value of the entry
|
||||
//! \return True if successful, false otherwise
|
||||
bool add_entry( Elf_Half value )
|
||||
{
|
||||
if ( !versym_section ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
versym_section->append_data( (const char*)&value, sizeof( Elf_Half ) );
|
||||
++entries_num;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
S* versym_section = nullptr; //!< Pointer to the section
|
||||
Elf_Word entries_num = 0; //!< Number of entries
|
||||
};
|
||||
|
||||
using versym_section_accessor = versym_section_accessor_template<section>;
|
||||
using const_versym_section_accessor =
|
||||
versym_section_accessor_template<const section>;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class versym_r_section_accessor_template
|
||||
//! \brief Class for accessing version requirement section data
|
||||
template <class S> class versym_r_section_accessor_template
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Constructor
|
||||
//! \param elf_file Reference to the ELF file
|
||||
//! \param versym_r_section Pointer to the version requirement section
|
||||
versym_r_section_accessor_template( const elfio& elf_file,
|
||||
S* versym_r_section )
|
||||
: elf_file( elf_file ), versym_r_section( versym_r_section ),
|
||||
entries_num( 0 )
|
||||
{
|
||||
// Find .dynamic section
|
||||
const section* dynamic_section = elf_file.sections[".dynamic"];
|
||||
|
||||
if ( dynamic_section == nullptr ) {
|
||||
return;
|
||||
}
|
||||
|
||||
const_dynamic_section_accessor dynamic_section_acc( elf_file,
|
||||
dynamic_section );
|
||||
Elf_Xword dyn_sec_num = dynamic_section_acc.get_entries_num();
|
||||
for ( Elf_Xword i = 0; i < dyn_sec_num; ++i ) {
|
||||
Elf_Xword tag;
|
||||
Elf_Xword value;
|
||||
std::string str;
|
||||
|
||||
if ( dynamic_section_acc.get_entry( i, tag, value, str ) &&
|
||||
tag == DT_VERNEEDNUM ) {
|
||||
entries_num = (Elf_Word)value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the number of entries
|
||||
//! \return Number of entries
|
||||
Elf_Word get_entries_num() const { return entries_num; }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get an entry
|
||||
//! \param no Index of the entry
|
||||
//! \param version Version of the entry
|
||||
//! \param file_name File name of the entry
|
||||
//! \param hash Hash of the entry
|
||||
//! \param flags Flags of the entry
|
||||
//! \param other Other information of the entry
|
||||
//! \param dep_name Dependency name of the entry
|
||||
//! \return True if successful, false otherwise
|
||||
bool get_entry( Elf_Word no,
|
||||
Elf_Half& version,
|
||||
std::string& file_name,
|
||||
Elf_Word& hash,
|
||||
Elf_Half& flags,
|
||||
Elf_Half& other,
|
||||
std::string& dep_name ) const
|
||||
{
|
||||
if ( versym_r_section == nullptr || ( no >= get_entries_num() ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const_string_section_accessor string_section_acc(
|
||||
elf_file.sections[versym_r_section->get_link()] );
|
||||
|
||||
Elfxx_Verneed* verneed = (Elfxx_Verneed*)versym_r_section->get_data();
|
||||
Elfxx_Vernaux* veraux =
|
||||
(Elfxx_Vernaux*)( (char*)verneed + verneed->vn_aux );
|
||||
for ( Elf_Word i = 0; i < no; ++i ) {
|
||||
verneed = (Elfxx_Verneed*)( (char*)verneed + verneed->vn_next );
|
||||
veraux = (Elfxx_Vernaux*)( (char*)verneed + verneed->vn_aux );
|
||||
}
|
||||
|
||||
version = verneed->vn_version;
|
||||
file_name = string_section_acc.get_string( verneed->vn_file );
|
||||
hash = veraux->vna_hash;
|
||||
flags = veraux->vna_flags;
|
||||
other = veraux->vna_other;
|
||||
dep_name = string_section_acc.get_string( veraux->vna_name );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
const elfio& elf_file;
|
||||
S* versym_r_section =
|
||||
nullptr; //!< Pointer to the version requirement section
|
||||
Elf_Word entries_num = 0; //!< Number of entries
|
||||
};
|
||||
|
||||
using versym_r_section_accessor = versym_r_section_accessor_template<section>;
|
||||
using const_versym_r_section_accessor =
|
||||
versym_r_section_accessor_template<const section>;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \class versym_d_section_accessor_template
|
||||
//! \brief Class for accessing version definition section data
|
||||
template <class S> class versym_d_section_accessor_template
|
||||
{
|
||||
public:
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Constructor
|
||||
//! \param elf_file Reference to the ELF file
|
||||
//! \param versym_d_section Pointer to the version definition section
|
||||
versym_d_section_accessor_template( const elfio& elf_file,
|
||||
S* versym_d_section )
|
||||
: elf_file( elf_file ), versym_d_section( versym_d_section ),
|
||||
entries_num( 0 )
|
||||
{
|
||||
// Find .dynamic section
|
||||
const section* dynamic_section = elf_file.sections[".dynamic"];
|
||||
|
||||
if ( dynamic_section == nullptr ) {
|
||||
return;
|
||||
}
|
||||
|
||||
const_dynamic_section_accessor dynamic_section_acc( elf_file,
|
||||
dynamic_section );
|
||||
Elf_Xword dyn_sec_num = dynamic_section_acc.get_entries_num();
|
||||
for ( Elf_Xword i = 0; i < dyn_sec_num; ++i ) {
|
||||
Elf_Xword tag;
|
||||
Elf_Xword value;
|
||||
std::string str;
|
||||
|
||||
if ( dynamic_section_acc.get_entry( i, tag, value, str ) &&
|
||||
tag == DT_VERDEFNUM ) {
|
||||
entries_num = (Elf_Word)value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get the number of entries
|
||||
//! \return Number of entries
|
||||
Elf_Word get_entries_num() const { return entries_num; }
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
//! \brief Get an entry
|
||||
//! \param no Index of the entry
|
||||
//! \param flags Flags of the entry
|
||||
//! \param version_index Version index of the entry
|
||||
//! \param hash Hash of the entry
|
||||
//! \param dep_name Dependency name of the entry
|
||||
//! \return True if successful, false otherwise
|
||||
bool get_entry( Elf_Word no,
|
||||
Elf_Half& flags,
|
||||
Elf_Half& version_index,
|
||||
Elf_Word& hash,
|
||||
std::string& dep_name ) const
|
||||
{
|
||||
if ( versym_d_section == nullptr || ( no >= get_entries_num() ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const_string_section_accessor string_section_acc(
|
||||
elf_file.sections[versym_d_section->get_link()] );
|
||||
|
||||
Elfxx_Verdef* verdef = (Elfxx_Verdef*)versym_d_section->get_data();
|
||||
Elfxx_Verdaux* verdaux =
|
||||
(Elfxx_Verdaux*)( (char*)verdef + verdef->vd_aux );
|
||||
for ( Elf_Word i = 0; i < no; ++i ) {
|
||||
verdef = (Elfxx_Verdef*)( (char*)verdef + verdef->vd_next );
|
||||
verdaux = (Elfxx_Verdaux*)( (char*)verdef + verdef->vd_aux );
|
||||
}
|
||||
|
||||
// verdef->vd_version should always be 1
|
||||
// see https://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-PDA/LSB-PDA.junk/symversion.html#VERDEFENTRIES
|
||||
// verdef->vd_cnt should always be 1.
|
||||
// see https://maskray.me/blog/2020-11-26-all-about-symbol-versioning
|
||||
|
||||
flags = verdef->vd_flags;
|
||||
version_index = verdef->vd_ndx;
|
||||
hash = verdef->vd_hash;
|
||||
dep_name = string_section_acc.get_string( verdaux->vda_name );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
private:
|
||||
const elfio& elf_file;
|
||||
S* versym_d_section =
|
||||
nullptr; //!< Pointer to the version definition section
|
||||
Elf_Word entries_num = 0; //!< Number of entries
|
||||
};
|
||||
|
||||
using versym_d_section_accessor = versym_d_section_accessor_template<section>;
|
||||
using const_versym_d_section_accessor =
|
||||
versym_d_section_accessor_template<const section>;
|
||||
|
||||
} // namespace ELFIO
|
||||
|
||||
#endif // ELFIO_VERSYM_HPP
|
||||
25830
vybuild/json.hpp
Normal file
25830
vybuild/json.hpp
Normal file
File diff suppressed because it is too large
Load Diff
3
vybuild/params.h
Normal file
3
vybuild/params.h
Normal file
@@ -0,0 +1,3 @@
|
||||
#define str(s) #s
|
||||
#define xstr(s) str(s)
|
||||
#include "params/params-sphincs-sha2-256f.h"
|
||||
85
vybuild/params/params-sphincs-sha2-256f.h
Normal file
85
vybuild/params/params-sphincs-sha2-256f.h
Normal file
@@ -0,0 +1,85 @@
|
||||
#ifndef SPX_PARAMS_H
|
||||
#define SPX_PARAMS_H
|
||||
|
||||
#define SPX_NAMESPACE(s) SPX_##s
|
||||
|
||||
/* Hash output length in bytes. */
|
||||
#define SPX_N 32
|
||||
/* Height of the hypertree. */
|
||||
#define SPX_FULL_HEIGHT 68
|
||||
/* Number of subtree layer. */
|
||||
#define SPX_D 17
|
||||
/* FORS tree dimensions. */
|
||||
#define SPX_FORS_HEIGHT 9
|
||||
#define SPX_FORS_TREES 35
|
||||
/* Winternitz parameter, */
|
||||
#define SPX_WOTS_W 16
|
||||
|
||||
/* The hash function is defined by linking a different hash.c file, as opposed
|
||||
to setting a #define constant. */
|
||||
|
||||
/* This is a SHA2-based parameter set, hence whether we use SHA-256
|
||||
* exclusively or we use both SHA-256 and SHA-512 is controlled by
|
||||
* the following #define */
|
||||
#define SPX_SHA512 1 /* Use SHA-512 for H and T_l, l >= 2 */
|
||||
|
||||
/* For clarity */
|
||||
#define SPX_ADDR_BYTES 32
|
||||
|
||||
/* WOTS parameters. */
|
||||
#if SPX_WOTS_W == 256
|
||||
#define SPX_WOTS_LOGW 8
|
||||
#elif SPX_WOTS_W == 16
|
||||
#define SPX_WOTS_LOGW 4
|
||||
#else
|
||||
#error SPX_WOTS_W assumed 16 or 256
|
||||
#endif
|
||||
|
||||
#define SPX_WOTS_LEN1 (8 * SPX_N / SPX_WOTS_LOGW)
|
||||
|
||||
/* SPX_WOTS_LEN2 is floor(log(len_1 * (w - 1)) / log(w)) + 1; we precompute */
|
||||
#if SPX_WOTS_W == 256
|
||||
#if SPX_N <= 1
|
||||
#define SPX_WOTS_LEN2 1
|
||||
#elif SPX_N <= 256
|
||||
#define SPX_WOTS_LEN2 2
|
||||
#else
|
||||
#error Did not precompute SPX_WOTS_LEN2 for n outside {2, .., 256}
|
||||
#endif
|
||||
#elif SPX_WOTS_W == 16
|
||||
#if SPX_N <= 8
|
||||
#define SPX_WOTS_LEN2 2
|
||||
#elif SPX_N <= 136
|
||||
#define SPX_WOTS_LEN2 3
|
||||
#elif SPX_N <= 256
|
||||
#define SPX_WOTS_LEN2 4
|
||||
#else
|
||||
#error Did not precompute SPX_WOTS_LEN2 for n outside {2, .., 256}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#define SPX_WOTS_LEN (SPX_WOTS_LEN1 + SPX_WOTS_LEN2)
|
||||
#define SPX_WOTS_BYTES (SPX_WOTS_LEN * SPX_N)
|
||||
#define SPX_WOTS_PK_BYTES SPX_WOTS_BYTES
|
||||
|
||||
/* Subtree size. */
|
||||
#define SPX_TREE_HEIGHT (SPX_FULL_HEIGHT / SPX_D)
|
||||
|
||||
#if SPX_TREE_HEIGHT * SPX_D != SPX_FULL_HEIGHT
|
||||
#error SPX_D should always divide SPX_FULL_HEIGHT
|
||||
#endif
|
||||
|
||||
/* FORS parameters. */
|
||||
#define SPX_FORS_MSG_BYTES ((SPX_FORS_HEIGHT * SPX_FORS_TREES + 7) / 8)
|
||||
#define SPX_FORS_BYTES ((SPX_FORS_HEIGHT + 1) * SPX_FORS_TREES * SPX_N)
|
||||
#define SPX_FORS_PK_BYTES SPX_N
|
||||
|
||||
/* Resulting SPX sizes. */
|
||||
#define SPX_BYTES (SPX_N + SPX_FORS_BYTES + SPX_D * SPX_WOTS_BYTES +\
|
||||
SPX_FULL_HEIGHT * SPX_N)
|
||||
#define SPX_PK_BYTES (2 * SPX_N)
|
||||
#define SPX_SK_BYTES (2 * SPX_N + SPX_PK_BYTES)
|
||||
|
||||
#include "../sha2_offsets.h"
|
||||
|
||||
#endif
|
||||
20
vybuild/sha2_offsets.h
Normal file
20
vybuild/sha2_offsets.h
Normal file
@@ -0,0 +1,20 @@
|
||||
#ifndef SHA2_OFFSETS_H_
|
||||
#define SHA2_OFFSETS_H_
|
||||
|
||||
/*
|
||||
* Offsets of various fields in the address structure when we use SHA2 as
|
||||
* the Sphincs+ hash function
|
||||
*/
|
||||
|
||||
#define SPX_OFFSET_LAYER 0 /* The byte used to specify the Merkle tree layer */
|
||||
#define SPX_OFFSET_TREE 1 /* The start of the 8 byte field used to specify the tree */
|
||||
#define SPX_OFFSET_TYPE 9 /* The byte used to specify the hash type (reason) */
|
||||
#define SPX_OFFSET_KP_ADDR 10 /* The start of the 4 byte field used to specify the key pair address */
|
||||
#define SPX_OFFSET_CHAIN_ADDR 17 /* The byte used to specify the chain address (which Winternitz chain) */
|
||||
#define SPX_OFFSET_HASH_ADDR 21 /* The byte used to specify the hash address (where in the Winternitz chain) */
|
||||
#define SPX_OFFSET_TREE_HGT 17 /* The byte used to specify the height of this node in the FORS or Merkle tree */
|
||||
#define SPX_OFFSET_TREE_INDEX 18 /* The start of the 4 byte field used to specify the node in the FORS or Merkle tree */
|
||||
|
||||
#define SPX_SHA2 1
|
||||
|
||||
#endif /* SHA2_OFFSETS_H_ */
|
||||
2132
vybuild/vybuild-actions.cpp
Normal file
2132
vybuild/vybuild-actions.cpp
Normal file
File diff suppressed because it is too large
Load Diff
78
vybuild/vybuild-cache.cpp
Normal file
78
vybuild/vybuild-cache.cpp
Normal file
@@ -0,0 +1,78 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "vybuild.hpp"
|
||||
#include <unordered_set>
|
||||
#include <mutex>
|
||||
#define XXH_INLINE_ALL
|
||||
using namespace std;
|
||||
fs::path cache_directory;
|
||||
fs::path smart_cache_directory;
|
||||
bool smart_cache_enabled=false;
|
||||
unordered_set<string> used_elements;
|
||||
mutex cache_mutex;
|
||||
void vybuild::cache::init_cache(bool enable_smart_cache) {
|
||||
fs::path cache_dir=fs::current_path()/".vybuild_cache";
|
||||
fs::path smart_cache_dir=fs::current_path()/".vybuild_scache";
|
||||
cache_directory=cache_dir;
|
||||
smart_cache_directory=smart_cache_dir;
|
||||
if (fs::exists(cache_dir) && !fs::is_directory(cache_dir)) {
|
||||
fs::remove(cache_dir);
|
||||
}
|
||||
fs::create_directories(cache_dir);
|
||||
if (fs::exists(smart_cache_dir)) {
|
||||
fs::remove_all(smart_cache_dir);
|
||||
}
|
||||
if (enable_smart_cache) {
|
||||
if (fs::exists(smart_cache_dir)) {
|
||||
fs::remove_all(smart_cache_dir);
|
||||
}
|
||||
fs::create_directories(smart_cache_dir);
|
||||
}
|
||||
smart_cache_enabled=enable_smart_cache;
|
||||
return;
|
||||
}
|
||||
void vybuild::cache::store_file(string key,fs::path file_path) {
|
||||
if (!std::all_of(key.begin(),key.end(),::isxdigit)) throw runtime_error("Invalid cache key.");
|
||||
if (!fs::exists(file_path)) throw std::runtime_error("Element named "+file_path.string()+" can't be put in cache: it doesn't exist.");
|
||||
if (!fs::is_regular_file(file_path)) throw std::runtime_error("Element named "+file_path.string()+" can't be put in cache: it is not a regular file.");
|
||||
auto final=cache_directory/key;
|
||||
auto tmp=final;
|
||||
tmp+=".tmp";
|
||||
fs::copy_file(file_path,tmp,fs::copy_options::overwrite_existing);
|
||||
fs::rename(tmp,final);
|
||||
{
|
||||
lock_guard<mutex> lock(cache_mutex);
|
||||
if (smart_cache_enabled) used_elements.emplace(key);
|
||||
}
|
||||
return;
|
||||
}
|
||||
bool vybuild::cache::cache_contains(string key) {
|
||||
if (fs::exists(cache_directory/key)) return true;
|
||||
return false;
|
||||
}
|
||||
void vybuild::cache::extract_file(string key,fs::path output_path) {
|
||||
if (!cache_contains(key)) throw runtime_error("Cache doesn't contain that key: "+key);
|
||||
auto source=cache_directory/key;
|
||||
auto tmp=output_path;
|
||||
tmp+=".tmp";
|
||||
fs::copy_file(source,tmp,fs::copy_options::overwrite_existing);
|
||||
fs::rename(tmp,output_path);
|
||||
{
|
||||
lock_guard<mutex> lock(cache_mutex);
|
||||
if (smart_cache_enabled) used_elements.emplace(key);
|
||||
}
|
||||
return;
|
||||
}
|
||||
string vybuild::cache::xxhash_to_string(XXH128_hash_t hash) {
|
||||
ostringstream oss;
|
||||
oss<<hex<<setfill('0')<<setw(16)<<hash.low64<<setw(16)<<hash.high64;
|
||||
return oss.str();
|
||||
}
|
||||
void vybuild::cache::clean_cache() {
|
||||
if (!smart_cache_enabled) return;
|
||||
for (auto &p:used_elements) {
|
||||
if (fs::exists(cache_directory/p)) fs::rename(cache_directory/p,smart_cache_directory/p);
|
||||
}
|
||||
fs::remove_all(cache_directory);
|
||||
fs::rename(smart_cache_directory,cache_directory);
|
||||
return;
|
||||
}
|
||||
96
vybuild/vybuild-condition.cpp
Normal file
96
vybuild/vybuild-condition.cpp
Normal file
@@ -0,0 +1,96 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "vybuild.hpp"
|
||||
#include "json.hpp"
|
||||
#include "xxhash.h"
|
||||
using namespace std;
|
||||
vector<string> conditions={"folder_exists",
|
||||
"folder_not_exists",
|
||||
"folder_empty",
|
||||
"folder_not_empty",
|
||||
"cache_contains",
|
||||
"cache_not_contains",
|
||||
"var_exists",
|
||||
"var_not_exists",
|
||||
"var_equals",
|
||||
"var_not_equals"};
|
||||
bool vybuild::condition::evaluate_condition(const json &condition) {
|
||||
vybuild::actions::check_arg_string(condition,"condition");
|
||||
vybuild::actions::check_arg_vector_string(condition,"condition_args");
|
||||
string cond_name=condition["condition"].get<string>();
|
||||
if (condition["condition_variables"].get<bool>()) cond_name=vybuild::parser::string_vars(cond_name);
|
||||
if (find(conditions.begin(),conditions.end(),cond_name)==conditions.end()) {
|
||||
throw std::runtime_error("Invalid condition: "+cond_name);
|
||||
}
|
||||
vector<string> cond_args=condition["condition_args"].get<vector<string>>();
|
||||
if (condition["condition_args_variables"].get<bool>()) cond_args=vybuild::parser::vector_string_vars(cond_args);
|
||||
if (cond_name=="folder_exists") {
|
||||
if (cond_args.size()!=1) {
|
||||
throw std::runtime_error("Wrong amount of arguments for condition \""+cond_name+"\". Expected 1, got "+to_string(cond_args.size())+".");
|
||||
}
|
||||
return fs::exists(cond_args[0]);
|
||||
} else if (cond_name=="folder_not_exists") {
|
||||
if (cond_args.size()!=1) {
|
||||
throw std::runtime_error("Wrong amount of arguments for condition \""+cond_name+"\". Expected 1, got "+to_string(cond_args.size())+".");
|
||||
}
|
||||
return !fs::exists(cond_args[0]);
|
||||
} else if (cond_name=="folder_empty") {
|
||||
if (cond_args.size()!=1) {
|
||||
throw std::runtime_error("Wrong amount of arguments for condition \""+cond_name+"\". Expected 1, got "+to_string(cond_args.size())+".");
|
||||
}
|
||||
size_t nb_elements=0;
|
||||
for (const auto& element:fs::directory_iterator(cond_args[0])) {
|
||||
++nb_elements;
|
||||
}
|
||||
return nb_elements==0;
|
||||
} else if (cond_name=="folder_not_empty") {
|
||||
if (cond_args.size()!=1) {
|
||||
throw std::runtime_error("Wrong amount of arguments for condition \""+cond_name+"\". Expected 1, got "+to_string(cond_args.size())+".");
|
||||
}
|
||||
size_t nb_elements=0;
|
||||
for (const auto& element:fs::directory_iterator(cond_args[0])) {
|
||||
++nb_elements;
|
||||
}
|
||||
return nb_elements!=0;
|
||||
} else if (cond_name=="cache_contains") {
|
||||
if (cond_args.size()!=1) {
|
||||
throw std::runtime_error("Wrong amount of arguments for condition \""+cond_name+"\". Expected 1, got "+to_string(cond_args.size())+".");
|
||||
}
|
||||
string key=vybuild::cache::xxhash_to_string(XXH3_128bits(cond_args[0].c_str(),cond_args[0].size()));
|
||||
return vybuild::cache::cache_contains(key);
|
||||
} else if (cond_name=="cache_not_contains") {
|
||||
if (cond_args.size()!=1) {
|
||||
throw std::runtime_error("Wrong amount of arguments for condition \""+cond_name+"\". Expected 1, got "+to_string(cond_args.size())+".");
|
||||
}
|
||||
string key=vybuild::cache::xxhash_to_string(XXH3_128bits(cond_args[0].c_str(),cond_args[0].size()));
|
||||
return !vybuild::cache::cache_contains(key);
|
||||
} else if (cond_name=="var_exists") {
|
||||
if (cond_args.size()!=1) {
|
||||
throw std::runtime_error("Wrong amount of arguments for condition \""+cond_name+"\". Expected 1, got "+to_string(cond_args.size())+".");
|
||||
}
|
||||
auto globals_vars_name=vybuild::vars::get_global_variables_list();
|
||||
return (find(globals_vars_name.begin(),globals_vars_name.end(),cond_args[0])!=globals_vars_name.end());
|
||||
} else if (cond_name=="var_not_exists") {
|
||||
if (cond_args.size()!=1) {
|
||||
throw std::runtime_error("Wrong amount of arguments for condition \""+cond_name+"\". Expected 1, got "+to_string(cond_args.size())+".");
|
||||
}
|
||||
auto globals_vars_name=vybuild::vars::get_global_variables_list();
|
||||
return !(find(globals_vars_name.begin(),globals_vars_name.end(),cond_args[0])!=globals_vars_name.end());
|
||||
} else if (cond_name=="var_equals") {
|
||||
if (cond_args.size()!=2) {
|
||||
throw std::runtime_error("Wrong amount of arguments for condition \""+cond_name+"\". Expected 2, got "+to_string(cond_args.size())+".");
|
||||
}
|
||||
auto globals_vars_name=vybuild::vars::get_global_variables_list();
|
||||
if (find(globals_vars_name.begin(),globals_vars_name.end(),cond_args[0])==globals_vars_name.end()) throw std::runtime_error("Variable named \""+cond_args[0]+"\" doesn't exists.");
|
||||
string var_value=vybuild::vars::get_global_variable(cond_args[0]);
|
||||
return var_value==cond_args[1];
|
||||
} else if (cond_name=="var_not_equals") {
|
||||
if (cond_args.size()!=2) {
|
||||
throw std::runtime_error("Wrong amount of arguments for condition \""+cond_name+"\". Expected 2, got "+to_string(cond_args.size())+".");
|
||||
}
|
||||
auto globals_vars_name=vybuild::vars::get_global_variables_list();
|
||||
if (find(globals_vars_name.begin(),globals_vars_name.end(),cond_args[0])==globals_vars_name.end()) throw std::runtime_error("Variable named \""+cond_args[0]+"\" doesn't exists.");
|
||||
string var_value=vybuild::vars::get_global_variable(cond_args[0]);
|
||||
return var_value!=cond_args[1];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
183
vybuild/vybuild-disk.cpp
Normal file
183
vybuild/vybuild-disk.cpp
Normal file
@@ -0,0 +1,183 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "vybuild.hpp"
|
||||
#include <zlib.h>
|
||||
using namespace std;
|
||||
#pragma pack(1)
|
||||
struct mbr_entry {
|
||||
uint8_t boot_indicator=0x00;
|
||||
uint8_t start_chs[3]={0,0x02,0};
|
||||
uint8_t partition_type=0xEE;
|
||||
uint8_t end_chs[3]={0xFF,0xFF,0xFF};
|
||||
uint32_t start_lba=1;
|
||||
uint32_t last_lba=0xFFFFFFFF;
|
||||
};
|
||||
#pragma pack()
|
||||
#pragma pack(1)
|
||||
struct mbr_protect {
|
||||
uint8_t bootstrap_code[440];
|
||||
uint32_t disk_signature;
|
||||
uint16_t reserved=0;
|
||||
mbr_entry first_entry;
|
||||
uint8_t other_entries[48]={0};
|
||||
uint16_t signature=0xAA55;
|
||||
};
|
||||
#pragma pack()
|
||||
#pragma pack(1)
|
||||
struct gpt_header {
|
||||
char signature[8]={'E','F','I',' ','P','A','R','T'};
|
||||
uint32_t revision=0x00010000;
|
||||
uint32_t header_size=92;
|
||||
uint32_t header_crc32;
|
||||
uint32_t reserved=0;
|
||||
uint64_t current_lba=1;
|
||||
uint64_t backup_lba;
|
||||
uint64_t first_usable_lba;
|
||||
uint64_t last_usable_lba;
|
||||
uint8_t disk_guid[16];
|
||||
uint64_t partition_entries_lba=2;
|
||||
uint32_t num_partitions_entries=128;
|
||||
uint32_t size_of_partitions_entries=128;
|
||||
uint32_t partitions_entries_crc32;
|
||||
};
|
||||
#pragma pack()
|
||||
#pragma pack(1)
|
||||
struct partition_entry {
|
||||
uint8_t type_guid[16];
|
||||
uint8_t unique_guid[16];
|
||||
uint64_t start_lba;
|
||||
uint64_t last_lba;
|
||||
uint64_t attributes;
|
||||
uint16_t name[36];
|
||||
};
|
||||
#pragma pack()
|
||||
struct disk_container {
|
||||
mbr_protect mbr;
|
||||
gpt_header header;
|
||||
array<partition_entry,128> parts;
|
||||
vector<uint8_t> data;
|
||||
size_t part_count=0;
|
||||
size_t lba_bumb=0;
|
||||
};
|
||||
array<uint8_t,16> vybuild::disk::uuid4_to_bytes(const string& uuid) {
|
||||
array<uint8_t,16> raw{};
|
||||
int byte_index=0;
|
||||
for (size_t i=0;i<uuid.size();i++) {
|
||||
char c=uuid[i];
|
||||
if (c=='-') continue;
|
||||
auto hex_val=[](char x) -> uint8_t {
|
||||
if (x>='0' && x<='9') return x-'0';
|
||||
if (x>='a' && x<='f') return x-'a'+10;
|
||||
if (x>='A' && x<='F') return x-'A'+10;
|
||||
throw std::runtime_error("Invalid hex char in UUID.");
|
||||
};
|
||||
uint8_t high=hex_val(c);
|
||||
if (++i>=uuid.size()) throw std::runtime_error("Malformed UUID.");
|
||||
uint8_t low=hex_val(uuid[i]);
|
||||
if (byte_index>=16) throw std::runtime_error("UUID too long.");
|
||||
raw[byte_index++]=(high<<4)|low;
|
||||
}
|
||||
if (byte_index!=16) throw std::runtime_error("Invalid UUID size.");
|
||||
array<uint8_t,16> out{};
|
||||
out[0]=raw[3];
|
||||
out[1]=raw[2];
|
||||
out[2]=raw[1];
|
||||
out[3]=raw[0];
|
||||
out[4]=raw[5];
|
||||
out[5]=raw[4];
|
||||
out[6]=raw[7];
|
||||
out[7]=raw[6];
|
||||
for (size_t i=8;i<16;i++) out[i]=raw[i];
|
||||
return out;
|
||||
}
|
||||
map<string,disk_container> disk_map;
|
||||
void vybuild::disk::create_disk(string key,size_t size,string disk_guid) {
|
||||
if (size%512!=0) throw std::runtime_error("Disk image size isn't a multiple of 512 bytes.");
|
||||
disk_container cont;
|
||||
size_t lba_count=size/512;
|
||||
size_t last_lba=lba_count-1;
|
||||
cont.header.backup_lba=last_lba;
|
||||
size_t first_usable_lba=2+((cont.header.size_of_partitions_entries*cont.header.num_partitions_entries)/512);
|
||||
cont.header.first_usable_lba=first_usable_lba;
|
||||
cont.header.last_usable_lba=last_lba-1;
|
||||
auto disk_id=uuid4_to_bytes(disk_guid);
|
||||
memcpy(cont.header.disk_guid,disk_id.data(),16);
|
||||
memset(cont.parts.data(),0,sizeof(cont.parts));
|
||||
cont.header.partitions_entries_crc32=crc32(0,(uint8_t*)cont.parts.data(),sizeof(cont.parts));
|
||||
cont.header.header_crc32=0;
|
||||
cont.header.header_crc32=crc32(0,(uint8_t*)&cont.header,sizeof(cont.header));
|
||||
cont.data.resize((cont.header.last_usable_lba-cont.header.first_usable_lba)*512);
|
||||
disk_map[key]=cont;
|
||||
return;
|
||||
}
|
||||
array<uint16_t,36> gpt_name_to_utf16le(const string& str) {
|
||||
std::array<uint16_t,36> out{};
|
||||
size_t len=str.size();
|
||||
if (len>35) len=35;
|
||||
for (size_t i=0;i<len;i++) out[i]=static_cast<uint16_t>(static_cast<unsigned char>(str[i]));
|
||||
out[len]=0;
|
||||
return out;
|
||||
}
|
||||
void add_partition(disk_container& disk,size_t partition_size_bytes,string type_guid,string unique_guid,uint64_t attributes,string name,uint8_t* in_buf,size_t in_size) {
|
||||
if (partition_size_bytes==0 || partition_size_bytes%512!=0) throw std::runtime_error("Invalid partition size.");
|
||||
if ((disk.lba_bumb*512)+partition_size_bytes>=disk.data.size()) throw std::runtime_error("Provided partition size would overflow the disk.");
|
||||
if (in_size>partition_size_bytes) throw std::runtime_error("Provided buffer is too big for provided partition size.");
|
||||
if (disk.part_count==128) throw std::runtime_error("Too much partitions.");
|
||||
partition_entry entry{};
|
||||
entry.attributes=attributes;
|
||||
size_t lba_count=partition_size_bytes/512;
|
||||
entry.start_lba=disk.header.first_usable_lba+disk.lba_bumb;
|
||||
entry.last_lba=entry.start_lba+lba_count-1;
|
||||
auto gpt_name=gpt_name_to_utf16le(name);
|
||||
memcpy(entry.name,gpt_name.data(),sizeof(gpt_name));
|
||||
auto type=vybuild::disk::uuid4_to_bytes(type_guid);
|
||||
auto unique=vybuild::disk::uuid4_to_bytes(unique_guid);
|
||||
memcpy(entry.type_guid,type.data(),16);
|
||||
memcpy(entry.unique_guid,unique.data(),16);
|
||||
disk.parts[disk.part_count]=entry;
|
||||
memcpy(disk.data.data()+disk.lba_bumb*512,in_buf,in_size);
|
||||
disk.part_count++;
|
||||
disk.lba_bumb+=lba_count;
|
||||
return;
|
||||
}
|
||||
void vybuild::disk::add_partition(string key,size_t partition_size_bytes,string type_guid,string unique_guid,uint64_t attributes,string name,uint8_t *in_buf,size_t in_size) {
|
||||
if (disk_map.find(key)==disk_map.end()) throw std::runtime_error(key+" isn't a valid disk key.");
|
||||
disk_container& disk=disk_map[key];
|
||||
add_partition(disk,partition_size_bytes,type_guid,unique_guid,attributes,name,in_buf,in_size);
|
||||
return;
|
||||
}
|
||||
static void write_sector(vector<uint8_t>& out,size_t lba,const void* data,size_t size) {
|
||||
size_t offset=lba*512;
|
||||
if (out.size()<offset+size) out.resize(offset+size,0);
|
||||
memcpy(out.data()+offset,data,size);
|
||||
return;
|
||||
}
|
||||
vector<uint8_t> export_disk(disk_container& cont) {
|
||||
vector<uint8_t> disk;
|
||||
size_t total_sectors=(cont.header.backup_lba+1);
|
||||
disk.resize(total_sectors*512,0);
|
||||
write_sector(disk,0,&cont.mbr,sizeof(cont.mbr));
|
||||
gpt_header header=cont.header;
|
||||
auto parts_crc=crc32(0,(uint8_t*)cont.parts.data(),sizeof(cont.parts));
|
||||
header.partitions_entries_crc32=parts_crc;
|
||||
header.header_crc32=0;
|
||||
header.header_crc32=crc32(0,(uint8_t*)&header,sizeof(header));
|
||||
write_sector(disk,1,&header,sizeof(header));
|
||||
write_sector(disk,cont.header.partition_entries_lba,cont.parts.data(),sizeof(cont.parts));
|
||||
if (!cont.data.empty()) {
|
||||
size_t data_lba=cont.header.first_usable_lba;
|
||||
write_sector(disk,data_lba,cont.data.data(),cont.data.size());
|
||||
}
|
||||
write_sector(disk,cont.header.backup_lba-(sizeof(cont.parts)/512),cont.parts.data(),sizeof(cont.parts));
|
||||
gpt_header backup=cont.header;
|
||||
backup.current_lba=cont.header.backup_lba;
|
||||
backup.backup_lba=1;
|
||||
backup.header_crc32=0;
|
||||
backup.header_crc32=crc32(0,(uint8_t*)&backup,sizeof(backup));
|
||||
write_sector(disk,cont.header.backup_lba,&backup,sizeof(backup));
|
||||
return disk;
|
||||
}
|
||||
vector<uint8_t> vybuild::disk::export_disk(string key) {
|
||||
if (disk_map.find(key)==disk_map.end()) throw std::runtime_error(key+" isn't a valid disk key.");
|
||||
disk_container& fat=disk_map[key];
|
||||
return export_disk(fat);
|
||||
}
|
||||
489
vybuild/vybuild-fat32.cpp
Normal file
489
vybuild/vybuild-fat32.cpp
Normal file
@@ -0,0 +1,489 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
// Some parts of the following driver is made using this guide: https://elm-chan.org/docs/fat_e.html
|
||||
#include "vybuild.hpp"
|
||||
#include "common/versions.h"
|
||||
#include "api.h"
|
||||
#include <dlfcn.h>
|
||||
#include <map>
|
||||
using namespace std;
|
||||
typedef int (*crypto_sign_func_ptr)(uint8_t*,size_t*,const uint8_t*,size_t,const uint8_t*);
|
||||
typedef void* (*sha3_512_func_ptr)(const void*,size_t,void*,int);
|
||||
struct common_crypto_struct {
|
||||
crypto_sign_func_ptr crypto_sign;
|
||||
sha3_512_func_ptr sha3_512;
|
||||
};
|
||||
bool is_crypto_lib_available=false;
|
||||
struct common_crypto_struct common_crypto;
|
||||
uint64_t vftm_target_offset=0;
|
||||
vector<uint8_t> vftm_target_content;
|
||||
uint8_t manifest_keypair[CRYPTO_PUBLICKEYBYTES+CRYPTO_SECRETKEYBYTES]={0};
|
||||
bool vybuild::fat32::is_crypto_lib_loaded() {
|
||||
return is_crypto_lib_available;
|
||||
}
|
||||
bool vybuild::fat32::is_vftm_target_set() {
|
||||
return vftm_target_offset!=0;
|
||||
}
|
||||
uint8_t* vybuild::fat32::get_manifest_keypair_buffer() {
|
||||
return manifest_keypair;
|
||||
}
|
||||
void vybuild::fat32::load_crypto_lib(string path) {
|
||||
void *handle;
|
||||
handle=dlopen(path.c_str(),RTLD_LAZY | RTLD_LOCAL);
|
||||
if (!handle) {
|
||||
throw std::runtime_error("Something went wrong during the loading of libcommoncrypto.so: "+string(dlerror()));
|
||||
}
|
||||
struct common_crypto_struct crypto;
|
||||
crypto.crypto_sign=reinterpret_cast<crypto_sign_func_ptr>(dlsym(handle,"crypto_sign_signature"));
|
||||
crypto.sha3_512=reinterpret_cast<sha3_512_func_ptr>(dlsym(handle,"sha3"));
|
||||
char *error=dlerror();
|
||||
if (error!=NULL) {
|
||||
dlclose(handle);
|
||||
throw std::runtime_error("Something went wrong during the loading of symbols from libcommoncrypto.so: "+string(error));
|
||||
}
|
||||
common_crypto=crypto;
|
||||
is_crypto_lib_available=true;
|
||||
return;
|
||||
}
|
||||
#pragma pack(1)
|
||||
struct vystem_fat_trusted_manifest {
|
||||
uint8_t sig[8]={'V','y','F','a','t','S','i','g'};
|
||||
uint16_t manifest_version=VY_COMMON_VERSIONS_MANIFEST;
|
||||
uint16_t bootloader_version=VY_COMMON_VERSIONS_BOOTLOADER;
|
||||
uint32_t os_version=VY_COMMON_VERSIONS_OS;
|
||||
uint8_t fat_hash[64];
|
||||
uint8_t fat_build_id[32];
|
||||
uint64_t clusters_count;
|
||||
uint64_t bytes_per_sector;
|
||||
uint64_t sectors_per_cluster;
|
||||
uint64_t fat_size_bytes;
|
||||
uint64_t fat_offset_bytes;
|
||||
uint64_t bootloader_cluster_count;
|
||||
uint64_t bootloader_cluster_offset;
|
||||
uint64_t bootloader_build_id;
|
||||
uint8_t fat_header_hash[64];
|
||||
uint8_t bootloader_binary_hash[64];
|
||||
uint64_t signature_offset_bytes;
|
||||
uint64_t signature_size;
|
||||
uint8_t gpt_disk_guid[16];
|
||||
uint8_t gpt_efi_part_unique_guid[16];
|
||||
uint8_t manifest_hash[64];
|
||||
};
|
||||
#pragma pack()
|
||||
#pragma pack(1)
|
||||
struct fat32_header {
|
||||
uint8_t BS_JmpBoot[3]={0xeb,0x58,0x90};
|
||||
uint8_t BS_OEMName[8]={'V','Y','B','U','I','L','D','1'};
|
||||
uint16_t BPB_BytsPerSec=512;
|
||||
uint8_t BPB_SecPerClus=1;
|
||||
uint16_t BPB_RsvdSecCnt=32; // equivalent to 32 clusters
|
||||
uint8_t BPB_NumFATs=2;
|
||||
uint16_t BPB_RootEntCnt=0; // always 0 for FAT32
|
||||
uint16_t BPB_TotSec16=0;
|
||||
uint8_t BPB_Media=0xF8;
|
||||
uint16_t BPB_FATSz16=0;
|
||||
uint16_t BPB_SecPerTrk=0; // set to 0 because guide didn't indicate anything
|
||||
uint16_t BPB_NumHeads=0; // also set to 0 for same reason, useless on modern hardware
|
||||
uint32_t BPB_HiddSec=0; // i honestly don't know what value the UEFI firmware expect here, but i pray for it to work
|
||||
uint32_t BPB_TotSec32; // finally a useful field, amount of SECTORS in the whole fs
|
||||
uint32_t BPB_FATSz32; // amount of SECTORS in each FAT
|
||||
uint16_t BPB_ExtFlags=0; // too complicated for now
|
||||
uint16_t BPB_FSVer=0; // apparentaly not only FAT32 is very old and will never be updated, but current version is 0.0
|
||||
uint32_t BPB_RootClus=2; // root directory cluster
|
||||
uint16_t BPB_FSInfo=1; // this is an offset
|
||||
uint16_t BPB_BkBootSec=6; // this is also an offset
|
||||
uint8_t BPB_Reserved[12]={0}; // i wonder why so much useles space waster into reserved fields
|
||||
uint8_t BS_DrvNum=0x80; // hope this will work on UEFI firmware, i hate retrocompatibility, it lead to useles thing
|
||||
uint8_t BS_Reserved=0; // another useles field
|
||||
uint8_t BS_BootSig=0x29; // another signature
|
||||
uint32_t BS_VolID=0; // the guide want me to put a date and time here, but too bad, i'm lazy
|
||||
uint8_t BS_VolLab[11]={'V','Y','A','U','T','O','F','A','T','3','2'}; // yay, my custom volume label fit!
|
||||
uint8_t BS_FilSysType[8]={'F','A','T','3','2',' ',' ',' '}; // ok why not
|
||||
uint8_t BS_BootCode32[420]={0}; // who the fuck think this is a good idea to put a field so large into a fs header ?!
|
||||
uint16_t BS_Sign=0xAA55; // another signature
|
||||
}; // yeah, exactly 512 bytes
|
||||
#pragma pack()
|
||||
#define ENTRY_FLAG_RO 0x01
|
||||
#define ENTRY_FLAG_HIDDEN 0x02
|
||||
#define ENTRY_FLAG_SYSTEM 0x04
|
||||
#define ENTRY_FLAG_VOL_ID 0x08
|
||||
#define ENTRY_FLAG_IS_DIR 0x10
|
||||
#define ENTRY_FLAG_ARCHIVE 0x20
|
||||
#define ENTRY_FLAG_LFN 0x0F
|
||||
#pragma pack(1)
|
||||
struct dir_entry {
|
||||
char name[11];
|
||||
uint8_t attributes;
|
||||
uint8_t sfn_flags=0;
|
||||
uint8_t creation_time_tenth=0;
|
||||
uint16_t creation_time=0;
|
||||
uint16_t creation_date=0;
|
||||
uint16_t last_access_date=0;
|
||||
uint16_t upper_part_first_cluster;
|
||||
uint16_t last_time_change=0;
|
||||
uint16_t last_data_change=0;
|
||||
uint16_t lower_part_first_cluster=0;
|
||||
uint32_t file_size=0;
|
||||
};
|
||||
#pragma pack()
|
||||
#pragma pack(1)
|
||||
struct fat32_fsinfo {
|
||||
uint32_t FSI_LeadSig=0x41615252;
|
||||
uint8_t FSI_Reserved1[480]={0}; // what the actual fuck is this... i think we have a new record
|
||||
uint32_t FSI_StrucSig=0x61417272;
|
||||
uint32_t FSI_Free_Count=0xFFFFFFFF;
|
||||
uint32_t FSI_Nxt_Free=0xFFFFFFFF;
|
||||
uint8_t FSI_Reserved2[12]={0};
|
||||
uint32_t FSI_TrailSig=0xAA550000;
|
||||
};
|
||||
#pragma pack()
|
||||
struct fat32_container {
|
||||
fat32_header header;
|
||||
uint64_t fat_start_sector=header.BPB_RsvdSecCnt;
|
||||
uint64_t fat_total_sectors; // complete it with header.BPB_FATSz32 * header.BPB_NumFATs, amount of sectors in all FATs
|
||||
uint64_t data_start_sector; // complete with header.BPB_RsvdSecCnt + fat_total_sectors
|
||||
uint64_t data_total_sectors; // complete with header.BPB_TotSec32 - data_start_sector
|
||||
uint64_t clusters_count; // complete with data_total_sectors / header.BPB_SecPerClus
|
||||
uint64_t root_clusters_sector;
|
||||
vector<uint8_t> fat;
|
||||
vector<uint8_t> data;
|
||||
fat32_fsinfo fsinfo;
|
||||
};
|
||||
map<string,fat32_container> fs_map;
|
||||
vector<uint8_t> get_urandom(size_t n) {
|
||||
vector<uint8_t> out(n);
|
||||
ifstream urandom("/dev/urandom",ios::binary);
|
||||
if (!urandom.is_open()) {
|
||||
throw runtime_error("Couldn't open /dev/urandom.");
|
||||
}
|
||||
urandom.read(reinterpret_cast<char*>(out.data()),n);
|
||||
if (urandom.gcount()!=static_cast<streamsize>(n)) {
|
||||
throw runtime_error("Coudln't open /dev/urandom.");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
void read_sector(uint8_t *buf_start_ptr,size_t sector_index,uint8_t* out_buf) {
|
||||
size_t byte_offset=sector_index*512;
|
||||
memcpy(out_buf,buf_start_ptr+byte_offset,512);
|
||||
return;
|
||||
}
|
||||
void write_sector(uint8_t *buf_start_ptr,size_t sector_index,uint8_t* in_buf) {
|
||||
size_t byte_offset=sector_index*512;
|
||||
memcpy(buf_start_ptr+byte_offset,in_buf,512);
|
||||
return;
|
||||
}
|
||||
uint32_t fat_read_entry(fat32_container& cont,uint32_t cluster) {
|
||||
if (cluster>=cont.clusters_count+2) throw std::runtime_error("FAT cluster out of bounds");
|
||||
size_t offset=cluster*4;
|
||||
uint32_t value;
|
||||
memcpy(&value,cont.fat.data()+offset,4);
|
||||
return value & 0x0FFFFFFF;
|
||||
}
|
||||
void fat_write_entry(fat32_container& cont,uint32_t cluster,uint32_t value) {
|
||||
if (cluster>=cont.clusters_count+2) throw std::runtime_error("FAT cluster out of bounds");
|
||||
size_t offset=cluster*4;
|
||||
value&=0x0FFFFFFF;
|
||||
memcpy(cont.fat.data()+offset,&value,4);
|
||||
return;
|
||||
}
|
||||
vystem_fat_trusted_manifest generate_manifest(fat32_container& cont,string disk_guid_var,string efi_part_unique_guid_var) {
|
||||
if (!is_crypto_lib_available) throw std::runtime_error("Crypto library isn't available.");
|
||||
if (vftm_target_offset==0) throw std::runtime_error("VFTM target isn't set.");
|
||||
int zero_bytes=0;
|
||||
for (int i=0;i<sizeof(manifest_keypair);i++) {
|
||||
if (manifest_keypair[i]==0) {
|
||||
zero_bytes++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (zero_bytes==sizeof(manifest_keypair)) throw std::runtime_error("VFTM keypair isn't set.");
|
||||
vystem_fat_trusted_manifest vftm;
|
||||
uint32_t *f1=(uint32_t*)cont.fat.data();
|
||||
f1[0]=f1[1]=0;
|
||||
common_crypto.sha3_512(cont.fat.data(),cont.fat.size(),vftm.fat_hash,sizeof(vftm.fat_hash));
|
||||
fat_write_entry(cont,0,0x0FFFFFF8);
|
||||
fat_write_entry(cont,1,0xFFFFFFFF);
|
||||
auto fat_build_id=get_urandom(sizeof(vftm.fat_build_id));
|
||||
memcpy(vftm.fat_build_id,fat_build_id.data(),fat_build_id.size());
|
||||
vftm.clusters_count=cont.clusters_count;
|
||||
vftm.bytes_per_sector=cont.header.BPB_BytsPerSec;
|
||||
vftm.sectors_per_cluster=cont.header.BPB_SecPerClus;
|
||||
vftm.fat_size_bytes=cont.fat.size();
|
||||
vftm.fat_offset_bytes=cont.header.BPB_RsvdSecCnt*cont.header.BPB_BytsPerSec;
|
||||
vftm.bootloader_cluster_count=vftm_target_content.size()/(cont.header.BPB_BytsPerSec*cont.header.BPB_SecPerClus);
|
||||
vftm.bootloader_cluster_offset=vftm_target_offset;
|
||||
auto bootloader_build_id=get_urandom(8);
|
||||
memcpy(&vftm.bootloader_build_id,&bootloader_build_id,8);
|
||||
common_crypto.sha3_512(&cont.header,sizeof(cont.header),vftm.fat_header_hash,sizeof(vftm.fat_header_hash));
|
||||
common_crypto.sha3_512(vftm_target_content.data(),vftm_target_content.size(),vftm.bootloader_binary_hash,sizeof(vftm.bootloader_binary_hash));
|
||||
vftm.signature_offset_bytes=cont.header.BPB_TotSec32*cont.header.BPB_BytsPerSec;
|
||||
vftm.signature_size=CRYPTO_BYTES;
|
||||
auto disk_guid=vybuild::vars::get_global_variable("\\$"+disk_guid_var+"\\$");
|
||||
auto disk_guid_bytes=vybuild::disk::uuid4_to_bytes(disk_guid);
|
||||
memcpy(vftm.gpt_disk_guid,disk_guid_bytes.data(),disk_guid_bytes.size());
|
||||
auto efi_part_unique_guid=vybuild::vars::get_global_variable("\\$"+efi_part_unique_guid_var+"\\$");
|
||||
auto efi_part_unique_guid_bytes=vybuild::disk::uuid4_to_bytes(efi_part_unique_guid);
|
||||
memcpy(vftm.gpt_efi_part_unique_guid,efi_part_unique_guid_bytes.data(),efi_part_unique_guid_bytes.size());
|
||||
common_crypto.sha3_512(&vftm,sizeof(vftm)-64,vftm.manifest_hash,sizeof(vftm.manifest_hash));
|
||||
return vftm;
|
||||
}
|
||||
uint8_t* cluster_ptr(fat32_container& cont,uint32_t cluster) {
|
||||
size_t sector=(cluster-2)*cont.header.BPB_SecPerClus;
|
||||
return (uint8_t*)cont.data.data()+sector*512;
|
||||
}
|
||||
uint32_t fat_allocate_cluster(fat32_container& cont) {
|
||||
for (uint32_t i=2;i<cont.clusters_count+2;i++) {
|
||||
if (fat_read_entry(cont,i)==0) {
|
||||
fat_write_entry(cont,i,0x0FFFFFFF);
|
||||
memset(cluster_ptr(cont,i),0,cont.header.BPB_SecPerClus*512);
|
||||
return i;
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("Fat32 image full.");
|
||||
}
|
||||
bool dir_add_entry(fat32_container& cont,uint32_t dir_cluster,dir_entry& entry) {
|
||||
if (dir_cluster<2 || dir_cluster>=cont.clusters_count+2) throw std::runtime_error("Directory cluster out of bounds.");
|
||||
dir_entry* entries=reinterpret_cast<dir_entry*>(cluster_ptr(cont,dir_cluster));
|
||||
size_t max_entries=(cont.header.BPB_SecPerClus*512)/sizeof(dir_entry);
|
||||
for (size_t i=0;i<max_entries;i++) {
|
||||
if (entries[i].name[0]==0) {
|
||||
entries[i]=entry;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
void vybuild::fat32::create_fat32(string key,size_t size) {
|
||||
if (size%512!=0) throw std::runtime_error("Fat32 image size isn't a multiple of 512 bytes.");
|
||||
fat32_container cont;
|
||||
cont.header.BPB_TotSec32=size/512;
|
||||
uint32_t fat_sectors=1;
|
||||
while (true) {
|
||||
uint64_t data_sectors=cont.header.BPB_TotSec32-cont.header.BPB_RsvdSecCnt-fat_sectors*cont.header.BPB_NumFATs;
|
||||
uint64_t clusters=data_sectors/cont.header.BPB_SecPerClus;
|
||||
uint32_t new_fat_sectors=((clusters+2)*4+511)/512;
|
||||
if (new_fat_sectors==fat_sectors) break;
|
||||
fat_sectors=new_fat_sectors;
|
||||
}
|
||||
cont.header.BPB_FATSz32=fat_sectors;
|
||||
cont.fat_total_sectors=cont.header.BPB_FATSz32*cont.header.BPB_NumFATs;
|
||||
cont.data_start_sector=cont.header.BPB_RsvdSecCnt+cont.fat_total_sectors;
|
||||
cont.data_total_sectors=cont.header.BPB_TotSec32-cont.data_start_sector;
|
||||
cont.clusters_count=cont.data_total_sectors/cont.header.BPB_SecPerClus;
|
||||
cont.root_clusters_sector=cont.data_start_sector+(cont.header.BPB_RootClus-2)*cont.header.BPB_SecPerClus;
|
||||
cont.fat.resize(cont.header.BPB_FATSz32*512);
|
||||
memset(cont.fat.data(),0,cont.fat.size());
|
||||
fat_write_entry(cont,0,0x0FFFFFF8);
|
||||
fat_write_entry(cont,1,0xFFFFFFFF);
|
||||
fat_write_entry(cont,2,0x0FFFFFFF);
|
||||
cont.data.resize(cont.data_total_sectors*512);
|
||||
memset(cont.data.data(),0,cont.data.size());
|
||||
memset(cluster_ptr(cont,2),0,cont.header.BPB_SecPerClus*512);
|
||||
dir_entry label{};
|
||||
memset(label.name,' ',11);
|
||||
memcpy(label.name,"VYAUTOFAT32",11);
|
||||
label.attributes=ENTRY_FLAG_VOL_ID;
|
||||
label.lower_part_first_cluster=0;
|
||||
label.upper_part_first_cluster=0;
|
||||
label.file_size=0;
|
||||
dir_add_entry(cont,2,label);
|
||||
fs_map[key]=cont;
|
||||
return;
|
||||
}
|
||||
uint32_t path_find_dir_cluster(fat32_container& cont,string& path) {
|
||||
if (path.empty() || path[0]!='/') throw std::runtime_error("Path must be absolute.");
|
||||
if (path=="/") return 2;
|
||||
uint32_t current_cluster=2;
|
||||
size_t pos=1;
|
||||
while (pos<path.size()) {
|
||||
size_t next=path.find('/',pos);
|
||||
string part=(next==string::npos)?path.substr(pos):path.substr(pos,next-pos);
|
||||
char fat_name[11];
|
||||
memset(fat_name,' ',11);
|
||||
memcpy(fat_name,part.c_str(),min<size_t>(part.size(),8));
|
||||
dir_entry* entries=reinterpret_cast<dir_entry*>(cluster_ptr(cont,current_cluster));
|
||||
size_t max_entries=(cont.header.BPB_SecPerClus*512)/sizeof(dir_entry);
|
||||
bool found=false;
|
||||
for (size_t i=0;i<max_entries;i++) {
|
||||
if (entries[i].name[0]==0) break;
|
||||
if (!(entries[i].attributes & ENTRY_FLAG_IS_DIR)) continue;
|
||||
if (memcmp(entries[i].name,fat_name,11)==0) {
|
||||
current_cluster=(uint32_t(entries[i].upper_part_first_cluster)<<16)|entries[i].lower_part_first_cluster;
|
||||
found=true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) return 0;
|
||||
if (next==string::npos) break;
|
||||
pos=next+1;
|
||||
}
|
||||
return current_cluster;
|
||||
}
|
||||
uint32_t create_dir_path(fat32_container& cont,string& parent_folder,string& dir_name) {
|
||||
uint32_t parent_cluster=path_find_dir_cluster(cont,parent_folder);
|
||||
if (parent_cluster==0) throw std::runtime_error("Parent folder not found: "+parent_folder);
|
||||
uint32_t new_cluster=fat_allocate_cluster(cont);
|
||||
dir_entry entry{};
|
||||
memset(entry.name,' ', 11);
|
||||
memcpy(entry.name,dir_name.c_str(),min<size_t>(dir_name.size(),8));
|
||||
memcpy(entry.name+8," ",3);
|
||||
entry.attributes=ENTRY_FLAG_IS_DIR;
|
||||
entry.lower_part_first_cluster=new_cluster&0xFFFF;
|
||||
entry.upper_part_first_cluster=new_cluster>>16;
|
||||
entry.file_size=0;
|
||||
if (!dir_add_entry(cont,parent_cluster,entry)) throw std::runtime_error("Parent directory full.");
|
||||
dir_entry dot{};
|
||||
memset(dot.name,' ',11);
|
||||
memcpy(dot.name,". ",11);
|
||||
dot.attributes=ENTRY_FLAG_IS_DIR;
|
||||
dot.lower_part_first_cluster=new_cluster&0xFFFF;
|
||||
dot.upper_part_first_cluster=new_cluster>>16;
|
||||
dot.file_size=0;
|
||||
dir_entry dotdot{};
|
||||
memset(dotdot.name,' ',11);
|
||||
memcpy(dotdot.name,".. ",11);
|
||||
dotdot.attributes=ENTRY_FLAG_IS_DIR;
|
||||
dotdot.lower_part_first_cluster=parent_cluster&0xFFFF;
|
||||
dotdot.upper_part_first_cluster=parent_cluster>>16;
|
||||
dotdot.file_size=0;
|
||||
dir_add_entry(cont,new_cluster,dot);
|
||||
dir_add_entry(cont,new_cluster,dotdot);
|
||||
return new_cluster;
|
||||
}
|
||||
uint32_t create_dir(fat32_container& cont,string& full_path) {
|
||||
if (full_path.empty() || full_path[0]!='/') throw std::runtime_error("Path must be absolute.");
|
||||
size_t last_slash=full_path.find_last_of('/');
|
||||
if (last_slash==string::npos) throw std::runtime_error("Invalid path.");
|
||||
string parent=(last_slash==0)?"/":full_path.substr(0,last_slash);
|
||||
string dir_name=full_path.substr(last_slash+1);
|
||||
if (dir_name.empty()) throw std::runtime_error("Directory name is empty.");
|
||||
return create_dir_path(cont, parent, dir_name);
|
||||
}
|
||||
void vybuild::fat32::add_directory_fat32(string key,string full_path) {
|
||||
if (fs_map.find(key)==fs_map.end()) throw std::runtime_error(key+" isn't a valid Fat32 image key.");
|
||||
fat32_container& fat=fs_map[key];
|
||||
create_dir(fat,full_path);
|
||||
return;
|
||||
}
|
||||
uint32_t fat_allocate_chain(fat32_container& cont,uint32_t count) {
|
||||
if (count==0) throw std::runtime_error("Cluster chain size cannot be zero.");
|
||||
uint32_t max_cluster=cont.clusters_count+2;
|
||||
for (uint32_t start=2;start+count<=max_cluster;start++) {
|
||||
bool free=true;
|
||||
for (uint32_t i=0;i<count;i++) {
|
||||
if (fat_read_entry(cont,start+i)!=0) {
|
||||
free=false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!free) continue;
|
||||
for (uint32_t i=0;i<count-1;i++) {
|
||||
fat_write_entry(cont,start+i,start+i+1);
|
||||
}
|
||||
fat_write_entry(cont,start+count-1,0x0FFFFFFF);
|
||||
size_t cluster_size=cont.header.BPB_SecPerClus*512;
|
||||
memset(cluster_ptr(cont,start),0,cluster_size*count);
|
||||
return start;
|
||||
}
|
||||
throw std::runtime_error("Not enough contiguous clusters.");
|
||||
}
|
||||
uint32_t create_file(fat32_container& cont,string full_path,uint8_t *buffer_in,size_t file_size,bool is_vftm_target) {
|
||||
if (file_size!=0 && buffer_in==nullptr) throw std::runtime_error("Input buffer is null.");
|
||||
if (full_path.empty() || full_path[0]!='/') throw std::runtime_error("Path must be absolute.");
|
||||
size_t last_slash=full_path.find_last_of('/');
|
||||
if (last_slash==string::npos) throw std::runtime_error("Invalid path.");
|
||||
string parent=(last_slash==0)?"/":full_path.substr(0,last_slash);
|
||||
string file_name=full_path.substr(last_slash+1);
|
||||
if (file_name.empty()) throw std::runtime_error("File name is empty.");
|
||||
if (file_name.size()>12) throw std::runtime_error("File name including extension is too long.");
|
||||
size_t dot=file_name.find_last_of('.');
|
||||
if (dot==string::npos || dot==0) throw std::runtime_error("Invalid file name.");
|
||||
string name=file_name.substr(0,dot);
|
||||
string ext=file_name.substr(dot+1);
|
||||
if (ext.size()>3 || ext.size()==0) throw std::runtime_error("Invalid extension.");
|
||||
if (name.size()>8 || ext.size()==0) throw std::runtime_error("Invalid file name.");
|
||||
transform(name.begin(),name.end(),name.begin(),::toupper);
|
||||
transform(ext.begin(),ext.end(),ext.begin(),::toupper);
|
||||
uint32_t parent_cluster=path_find_dir_cluster(cont,parent);
|
||||
if (parent_cluster==0) throw std::runtime_error("Parent folder doesn't exist.");
|
||||
uint32_t cluster_size=cont.header.BPB_SecPerClus*512;
|
||||
uint32_t cluster_count=max<uint32_t>(1,(file_size+cluster_size-1)/cluster_size);
|
||||
uint32_t start_cluster=fat_allocate_chain(cont,cluster_count);
|
||||
dir_entry entry{};
|
||||
memset(entry.name,' ',11);
|
||||
memcpy(entry.name,name.c_str(),min<size_t>(name.size(),8));
|
||||
memcpy(entry.name+8,ext.data(),min<size_t>(ext.size(),3));
|
||||
entry.attributes=ENTRY_FLAG_ARCHIVE;
|
||||
entry.lower_part_first_cluster=start_cluster&0xFFFF;
|
||||
entry.upper_part_first_cluster=start_cluster>>16;
|
||||
entry.file_size=file_size;
|
||||
if (!dir_add_entry(cont,parent_cluster,entry)) throw std::runtime_error("Parent directory full.");
|
||||
memcpy(cluster_ptr(cont,start_cluster),buffer_in,file_size);
|
||||
if (is_vftm_target) {
|
||||
vftm_target_content.resize(cluster_count*cluster_size,0);
|
||||
memcpy(vftm_target_content.data(),buffer_in,file_size);
|
||||
vftm_target_offset=start_cluster;
|
||||
}
|
||||
return start_cluster;
|
||||
}
|
||||
void vybuild::fat32::add_file_fat32(string key,string full_path,uint8_t *buffer_in,size_t file_size,bool is_vftm_target) {
|
||||
if (fs_map.find(key)==fs_map.end()) throw std::runtime_error(key+" isn't a valid Fat32 image key.");
|
||||
fat32_container& fat=fs_map[key];
|
||||
create_file(fat,full_path,buffer_in,file_size,is_vftm_target);
|
||||
return;
|
||||
}
|
||||
void generate_vftm_sectors(const uint8_t* part_guid,int* s1,int* s2) {
|
||||
uint32_t h=0x811c9dc5;
|
||||
for (int i=0;i<16;i++) h=(h^part_guid[i])*0x01000193;
|
||||
*s1=8+(h%24);
|
||||
*s2=8+(((h>>16)%23+(*s1-7))%24);
|
||||
}
|
||||
void secure_erase(void *address,size_t size) {
|
||||
explicit_bzero(address,size);
|
||||
}
|
||||
vector<uint8_t> export_fat32(fat32_container& cont,bool generate_vftm,string disk_guid_var,string efi_part_unique_guid_var) {
|
||||
uint32_t total_sectors=cont.header.BPB_TotSec32;
|
||||
vector<uint8_t> img(total_sectors*512,0);
|
||||
auto write_sector=[&](uint32_t sector,const void* data,size_t size) {
|
||||
memcpy(img.data()+sector*512,data,size);
|
||||
};
|
||||
write_sector(0,&cont.header,sizeof(cont.header));
|
||||
write_sector(cont.header.BPB_BkBootSec,&cont.header,sizeof(cont.header));
|
||||
write_sector(1,&cont.fsinfo,sizeof(cont.fsinfo));
|
||||
write_sector(cont.header.BPB_BkBootSec+1,&cont.fsinfo,sizeof(cont.fsinfo));
|
||||
uint32_t fat_size_bytes=cont.header.BPB_FATSz32*512;
|
||||
uint32_t fat_sector_start=cont.header.BPB_RsvdSecCnt;
|
||||
memcpy(img.data()+fat_sector_start*512,cont.fat.data(),fat_size_bytes);
|
||||
uint32_t fat2_sector_start=fat_sector_start+cont.header.BPB_FATSz32;
|
||||
memcpy(img.data()+fat2_sector_start*512,cont.fat.data(),fat_size_bytes);
|
||||
uint32_t data_sector_start=cont.data_start_sector;
|
||||
memcpy(img.data()+data_sector_start*512,cont.data.data(),cont.data.size());
|
||||
if (generate_vftm) {
|
||||
auto efi_part_unique_guid=vybuild::vars::get_global_variable("\\$"+efi_part_unique_guid_var+"\\$");
|
||||
auto efi_part_unique_guid_bytes=vybuild::disk::uuid4_to_bytes(efi_part_unique_guid);
|
||||
auto vftm=generate_manifest(cont,disk_guid_var,efi_part_unique_guid_var);
|
||||
int manifest_sector,pk_manifest_sector;
|
||||
generate_vftm_sectors((uint8_t*)efi_part_unique_guid_bytes.data(),&manifest_sector,&pk_manifest_sector);
|
||||
uint8_t signature_manifest[CRYPTO_BYTES];
|
||||
size_t siglen;
|
||||
if (common_crypto.crypto_sign(signature_manifest,&siglen,(uint8_t*)&vftm,sizeof(vftm),manifest_keypair+CRYPTO_PUBLICKEYBYTES)) {
|
||||
secure_erase(manifest_keypair,sizeof(manifest_keypair));
|
||||
throw std::runtime_error("Couldn't sign VFTM.");
|
||||
}
|
||||
if (siglen!=CRYPTO_BYTES) {
|
||||
secure_erase(manifest_keypair,sizeof(manifest_keypair));
|
||||
throw std::runtime_error("The returned signature isn't the expected size.");
|
||||
}
|
||||
secure_erase(manifest_keypair+CRYPTO_PUBLICKEYBYTES,CRYPTO_SECRETKEYBYTES);
|
||||
memcpy(img.data()+manifest_sector*cont.header.BPB_BytsPerSec,&vftm,sizeof(vftm));
|
||||
memcpy(img.data()+pk_manifest_sector*cont.header.BPB_BytsPerSec,manifest_keypair,CRYPTO_PUBLICKEYBYTES);
|
||||
img.resize(img.size()+CRYPTO_BYTES);
|
||||
memcpy(img.data()+vftm.signature_offset_bytes,signature_manifest,CRYPTO_BYTES);
|
||||
}
|
||||
return img;
|
||||
}
|
||||
vector<uint8_t> vybuild::fat32::export_fat32(string key,bool generate_vftm,string disk_guid_var,string efi_part_unique_guid_var) {
|
||||
if (fs_map.find(key)==fs_map.end()) throw std::runtime_error(key+" isn't a valid Fat32 image key.");
|
||||
fat32_container& fat=fs_map[key];
|
||||
return export_fat32(fat,generate_vftm,disk_guid_var,efi_part_unique_guid_var);
|
||||
}
|
||||
55
vybuild/vybuild-parser.cpp
Normal file
55
vybuild/vybuild-parser.cpp
Normal file
@@ -0,0 +1,55 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "vybuild.hpp"
|
||||
#include <regex>
|
||||
using namespace std;
|
||||
namespace fs=filesystem;
|
||||
string vybuild::parser::root_folder_parsing(const string& root_folder,const string& file) {
|
||||
if (root_folder=="%filefolder%") {
|
||||
return fs::absolute(fs::path(file)).parent_path().string();
|
||||
} else if (root_folder=="%rootcallerfolder%") {
|
||||
return fs::absolute(vybuild::vars::get_global_variable("%rootcallerfolder%")).string();
|
||||
} else {
|
||||
return file;
|
||||
}
|
||||
}
|
||||
vector<string> vybuild::parser::vector_string_vars(vector<string> vector_in) {
|
||||
vector<string> out;
|
||||
for (auto arg:vector_in) {
|
||||
auto element=arg;
|
||||
for (auto var:vybuild::vars::get_global_variables_list()) {
|
||||
regex regvar(var);
|
||||
arg=regex_replace(arg,regvar,vybuild::vars::get_global_variable(var));
|
||||
}
|
||||
out.push_back(arg);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
string vybuild::parser::string_vars(string string_in) {
|
||||
string out=string_in;
|
||||
for (auto var:vybuild::vars::get_global_variables_list()) {
|
||||
regex regvar(var);
|
||||
out=regex_replace(out,regvar,vybuild::vars::get_global_variable(var));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
vector<string> vybuild::parser::vector_string_path_completions(vector<string> vector_in,string suffix) {
|
||||
vector<string> out;
|
||||
for (int i=0;i<vector_in.size();i++) {
|
||||
if (vector_in[i].ends_with(suffix)) {
|
||||
out.push_back(vector_in[i]);
|
||||
} else if (vector_in[i].ends_with("**")) {
|
||||
for (auto &file:fs::recursive_directory_iterator(vector_in[i].substr(0,vector_in[i].size()-2))) {
|
||||
if (file.path().string().ends_with(suffix)) {
|
||||
out.push_back(file.path().string());
|
||||
}
|
||||
}
|
||||
} else if (vector_in[i].ends_with("*")) {
|
||||
for (auto &file:fs::directory_iterator(vector_in[i].substr(0,vector_in[i].size()-3))) {
|
||||
if (file.path().string().ends_with(suffix)) {
|
||||
out.push_back(file.path().string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
23
vybuild/vybuild-vars.cpp
Normal file
23
vybuild/vybuild-vars.cpp
Normal file
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "vybuild.hpp"
|
||||
#include <map>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
vector<string> global_vars_list={};
|
||||
map<string,string> global_vars;
|
||||
vector<string>& vybuild::vars::get_global_variables_list() {
|
||||
return global_vars_list;
|
||||
}
|
||||
void vybuild::vars::set_global_variable(string key,string value) {
|
||||
global_vars[key]=value;
|
||||
global_vars_list.push_back(key);
|
||||
return;
|
||||
}
|
||||
string vybuild::vars::get_global_variable(string key) {
|
||||
if (key=="DISK_GUID") {
|
||||
for (auto &s:global_vars_list) {
|
||||
cout<<s<<endl;
|
||||
}
|
||||
}
|
||||
return global_vars.at(key);
|
||||
}
|
||||
795
vybuild/vybuild-vyld.cpp
Normal file
795
vybuild/vybuild-vyld.cpp
Normal file
@@ -0,0 +1,795 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "vybuild.hpp"
|
||||
#include <iostream>
|
||||
#include <unistd.h>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <queue>
|
||||
#include <mutex>
|
||||
#include <functional>
|
||||
#include <regex>
|
||||
#include <sys/wait.h>
|
||||
#include <wordexp.h>
|
||||
#include <random>
|
||||
#include "elfio.hpp"
|
||||
#include "common/versions.h"
|
||||
using namespace std;
|
||||
extern int get_deepness();
|
||||
queue<function<vybuild::actions::ActionStatus()>> vyld_compilation_tasks;
|
||||
mutex vyld_compilation_tasks_mutex;
|
||||
void print_deepness_vyld(string text) {
|
||||
cout<<"[VyBuild] ";
|
||||
for (int i=0;i<get_deepness();i++) {
|
||||
cout<<"│ ";
|
||||
}
|
||||
cout<<text<<endl;
|
||||
return;
|
||||
}
|
||||
string find_executable_vyld(const string& exe_name) {
|
||||
const char* path_env=getenv("PATH");
|
||||
if (!path_env) return "";
|
||||
string paths(path_env);
|
||||
stringstream ss(paths);
|
||||
string dir;
|
||||
while (std::getline(ss,dir,':')) {
|
||||
fs::path candidate=fs::path(dir)/exe_name;
|
||||
if (fs::exists(candidate) && fs::is_regular_file(candidate) && (fs::status(candidate).permissions() & fs::perms::owner_exec)!=fs::perms::none) {
|
||||
return candidate.string();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
vector<string> split_args_shell_vyld(const string& input) {
|
||||
wordexp_t result;
|
||||
vector<string> args;
|
||||
if (wordexp(input.c_str(),&result,0)==0) {
|
||||
for (size_t i=0;i<result.we_wordc;++i) {
|
||||
args.emplace_back(result.we_wordv[i]);
|
||||
}
|
||||
}
|
||||
wordfree(&result);
|
||||
return args;
|
||||
}
|
||||
string get_command_output_vyld(string command) {
|
||||
int pipefd[2];
|
||||
if (pipe(pipefd)==-1) {
|
||||
throw std::runtime_error("Couldn't create pipe for obtaining command output.");
|
||||
}
|
||||
pid_t pid=fork();
|
||||
if (pid<0) {
|
||||
throw std::runtime_error("Couldn't fork process.");
|
||||
}
|
||||
if (pid==0) {
|
||||
close(pipefd[0]);
|
||||
dup2(pipefd[1],STDOUT_FILENO);
|
||||
dup2(pipefd[1],STDERR_FILENO);
|
||||
close(pipefd[1]);
|
||||
std::vector<const char*> argv;
|
||||
auto args=split_args_shell_vyld(command);
|
||||
args[0]=find_executable_vyld(args[0]).c_str();
|
||||
for (auto &a:args) argv.push_back(a.c_str());
|
||||
argv.push_back(nullptr);
|
||||
execvp(argv[0],const_cast<char* const*>(argv.data()));
|
||||
cout<<string(strerror(errno))<<endl;
|
||||
throw std::runtime_error("Command failed.");
|
||||
_exit(1);
|
||||
} else {
|
||||
close(pipefd[1]);
|
||||
std::stringstream buffer;
|
||||
char c;
|
||||
while (read(pipefd[0],&c,1)>0) {
|
||||
buffer<<c;
|
||||
}
|
||||
close(pipefd[0]);
|
||||
int status;
|
||||
waitpid(pid,&status,0);
|
||||
if (!WIFEXITED(status)) {
|
||||
throw std::runtime_error("An error happened in forked process.");
|
||||
}
|
||||
return buffer.str();
|
||||
}
|
||||
}
|
||||
vector<string> headers_from_dfile_vyld(string dfile_path) {
|
||||
if (!fs::exists(dfile_path)) throw std::runtime_error(dfile_path+" doesn't exist.");
|
||||
ifstream dfile(dfile_path);
|
||||
vector<string> deps;
|
||||
string line,all;
|
||||
while (getline(dfile,line)) {
|
||||
if (!line.empty() && line.back()=='\\') {
|
||||
line.pop_back();
|
||||
all+=line+" ";
|
||||
} else {
|
||||
all+=line+ " ";
|
||||
}
|
||||
}
|
||||
auto pos=all.find(':');
|
||||
if (pos==string::npos) return deps;
|
||||
string rest=all.substr(pos+1);
|
||||
istringstream iss(rest);
|
||||
string token;
|
||||
while (iss>>token) {
|
||||
deps.push_back(token);
|
||||
}
|
||||
return deps;
|
||||
}
|
||||
struct vyx_addresses {
|
||||
uint64_t text_offset;
|
||||
uint64_t stack_base;
|
||||
};
|
||||
uint64_t rand_in_range(uint64_t min,uint64_t max) {
|
||||
static random_device rd;
|
||||
static mt19937_64 gen(rd());
|
||||
std::uniform_int_distribution<uint64_t> dis(min, max);
|
||||
return dis(gen);
|
||||
}
|
||||
uint64_t random_canonical(uint64_t start,uint64_t end) {
|
||||
uint64_t addr=rand_in_range(start/4096,end/4096)*4096;
|
||||
return addr;
|
||||
}
|
||||
vyx_addresses generate_vyx_addresses() {
|
||||
vyx_addresses addr;
|
||||
addr.text_offset=random_canonical(0xFFFF800000000000ULL,0xFFFF900000000000ULL-1);
|
||||
addr.stack_base=random_canonical(0xFFFFF00000000000ULL,0xFFFFFF8000000000ULL-0x100000ULL);
|
||||
return addr;
|
||||
}
|
||||
size_t pad_size(size_t value,size_t multiple) {
|
||||
if (multiple==0) return value;
|
||||
size_t remainder=value%multiple;
|
||||
if (remainder==0) return value;
|
||||
return value+multiple-remainder;
|
||||
}
|
||||
#pragma pack(1)
|
||||
struct payload_header {
|
||||
uint8_t sig[8]={'V','P','A','Y','L','O','A','D'};
|
||||
uint32_t payload_size_bytes=0;
|
||||
uint32_t payload_pages_count=0;
|
||||
uint8_t map_flags=0;
|
||||
uint64_t load_address=0;
|
||||
};
|
||||
#pragma pack()
|
||||
#define EXECUTABLE (1<<0)
|
||||
#define WRITABLE (1<<1)
|
||||
static bool char_to_value(char c,uint8_t &out) {
|
||||
if (c>='0' && c<='9') {
|
||||
out=c-'0';
|
||||
return true;
|
||||
}
|
||||
if (c>='a' && c<='f') {
|
||||
out=c-'a'+10;
|
||||
return true;
|
||||
}
|
||||
if (c>='A' && c<='F') {
|
||||
out=c-'A'+10;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
uint64_t string_hex_to_u64(const std::string &str){
|
||||
if (str.size()<3) return false;
|
||||
if (!(str[0]=='0' && (str[1]=='x'))) return false;
|
||||
uint64_t value=0;
|
||||
for (size_t i=2;i<str.size();i++) {
|
||||
uint8_t v=0;
|
||||
if (!char_to_value(str[i],v))return false;
|
||||
value=(value<<4)|v;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
vector<uint8_t> generate_payloads(const json& payloads) {
|
||||
vector<uint8_t> out={};
|
||||
if (payloads.size()==0) return out;
|
||||
for (auto &p:payloads) {
|
||||
if (!p.is_object()) throw std::runtime_error("Payload must be stored in a dictionnary.");
|
||||
vybuild::actions::check_arg_string(p,"source_file");
|
||||
if (!p.contains("is_executable")) throw std::runtime_error("Is executable isn't provided.");
|
||||
if (!p["is_executable"].is_boolean()) throw std::runtime_error("Is executable isn't a boolean.");
|
||||
if (!p.contains("is_writable")) throw std::runtime_error("Is writable isn't provided.");
|
||||
if (!p["is_writable"].is_boolean()) throw std::runtime_error("Is writbale isn't a boolean.");
|
||||
if (!p.contains("expected_va")) throw std::runtime_error("Expected VA isn't provided.");
|
||||
if (!p["expected_va"].is_string()) throw std::runtime_error("Expected VA isn't a string.");
|
||||
fs::path source_file=p["source_file"].get<string>();
|
||||
bool source_file_variables=p["source_file_variables"].get<bool>();
|
||||
if (source_file_variables) source_file=vybuild::parser::string_vars(source_file);
|
||||
if (!fs::exists(source_file)) throw std::runtime_error("Source file doesn't exist: "+source_file.string());
|
||||
if (!fs::is_regular_file(source_file)) throw std::runtime_error("Source file isn't a regular file: "+source_file.string());
|
||||
size_t payload_size=fs::file_size(source_file);
|
||||
size_t payload_page_count=pad_size(payload_size,4096)/4096;
|
||||
uint64_t va=string_hex_to_u64(p["expected_va"].get<string>());
|
||||
if (va==0 || va%4096!=0) throw std::runtime_error("Invalid expected VA: expected VA must be non null and 4KB aligned.");
|
||||
payload_header header;
|
||||
header.payload_size_bytes=payload_size;
|
||||
header.payload_pages_count=payload_page_count;
|
||||
header.load_address=va;
|
||||
if (p["is_executable"].get<bool>()) header.map_flags|=EXECUTABLE;
|
||||
if (p["is_writable"].get<bool>()) header.map_flags|=WRITABLE;
|
||||
ifstream payload_bin(source_file,ios::binary);
|
||||
if (!payload_bin) throw std::runtime_error("VyldCompilationAction: Cannot open payload source file: "+source_file.string());
|
||||
vector<uint8_t> payload_content(payload_size);
|
||||
payload_bin.read(reinterpret_cast<char*>(payload_content.data()),payload_size);
|
||||
if (!payload_bin) throw std::runtime_error("VyldCompilationAction: Cannot read payload source file: "+source_file.string());
|
||||
vector<uint8_t> final_payload(sizeof(payload_header));
|
||||
memcpy(final_payload.data(),(uint8_t*)&header,sizeof(payload_header));
|
||||
final_payload.insert(final_payload.end(),payload_content.begin(),payload_content.end());
|
||||
out.insert(out.end(),final_payload.begin(),final_payload.end());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
vybuild::actions::ActionStatus parallel_vyld_compilation(string source,string compiler_path,string compiler_hash,vector<string> compiler_args,string dfile_path,string header_command,string output_file) {
|
||||
if (compiler_hash!="") {
|
||||
string c_content="";
|
||||
auto vars_list=vybuild::vars::get_global_variables_list();
|
||||
if (header_command!="") {
|
||||
string dep_command=header_command;
|
||||
regex regvar1("%dfile%");
|
||||
dep_command=regex_replace(dep_command,regvar1,dfile_path);
|
||||
regex regvar2("%sourcefile%");
|
||||
dep_command=regex_replace(dep_command,regvar2,source);
|
||||
int res=std::system(dep_command.c_str());
|
||||
if (res!=0) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: Cannot get headers list for file \""+source+"\" with command: "+dep_command);
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
auto headers=headers_from_dfile_vyld(dfile_path);
|
||||
for (auto &h:headers) {
|
||||
ifstream header(h);
|
||||
vector<char> header_data(fs::file_size(fs::absolute(h)));
|
||||
if (!header) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: Couldn't open source/header file: "+h);
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
header.read(header_data.data(),header_data.size());
|
||||
if (!header) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: Couldn't read source/header file: "+h);
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
c_content+=string(header_data.begin(),header_data.end());
|
||||
header.close();
|
||||
}
|
||||
fs::remove(dfile_path);
|
||||
}
|
||||
c_content+="\n"+compiler_path;
|
||||
c_content+="\n"+compiler_hash;
|
||||
for (auto& a:compiler_args) c_content+="\n"+a;
|
||||
string key=vybuild::cache::xxhash_to_string(XXH3_128bits(c_content.data(),c_content.size()));
|
||||
if (vybuild::cache::cache_contains(key)) {
|
||||
vybuild::cache::extract_file(key,output_file);
|
||||
return vybuild::actions::ActionStatus::Success;
|
||||
}
|
||||
int pipefd[2];
|
||||
if (pipe(pipefd)==-1) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: An error happened while creating pipe.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
pid_t pid=fork();
|
||||
if (pid<0) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: An error happened while forking.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (pid==0) {
|
||||
close(pipefd[0]);
|
||||
dup2(pipefd[1],STDOUT_FILENO);
|
||||
dup2(pipefd[1],STDERR_FILENO);
|
||||
close(pipefd[1]);
|
||||
std::vector<const char*> argv={compiler_path.c_str()};
|
||||
argv.push_back("-c");
|
||||
argv.push_back(source.c_str());
|
||||
argv.push_back("-o");
|
||||
argv.push_back(output_file.c_str());
|
||||
for (int i=0;i<compiler_args.size();i++) {
|
||||
argv.push_back(compiler_args[i].c_str());
|
||||
}
|
||||
argv.push_back(nullptr);
|
||||
execvp(compiler_path.c_str(),const_cast<char* const*>(argv.data()));
|
||||
print_deepness_vyld("ParallelVyldCompilation: An error happened while executing command.");
|
||||
_exit(1);
|
||||
} else {
|
||||
close(pipefd[1]);
|
||||
std::stringstream buffer;
|
||||
char c;
|
||||
while (read(pipefd[0],&c,1)>0) {
|
||||
buffer<<c;
|
||||
}
|
||||
close(pipefd[0]);
|
||||
int status;
|
||||
waitpid(pid,&status,0);
|
||||
if (!WIFEXITED(status)) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: An error happened in forked process.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (WEXITSTATUS(status)!=0) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: Command exited with error (status "+to_string(WEXITSTATUS(status))+"), showing output:\n");
|
||||
cout<<buffer.str()<<endl;
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
} else {
|
||||
vybuild::cache::store_file(key,output_file);
|
||||
return vybuild::actions::ActionStatus::Success;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
int pipefd[2];
|
||||
if (pipe(pipefd)==-1) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: An error happened while creating pipe.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
pid_t pid=fork();
|
||||
if (pid<0) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: An error happened while forking.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (pid==0) {
|
||||
close(pipefd[0]);
|
||||
dup2(pipefd[1],STDOUT_FILENO);
|
||||
dup2(pipefd[1],STDERR_FILENO);
|
||||
close(pipefd[1]);
|
||||
std::vector<const char*> argv={compiler_path.c_str()};
|
||||
argv.push_back("-c");
|
||||
argv.push_back(source.c_str());
|
||||
argv.push_back("-o");
|
||||
argv.push_back(output_file.c_str());
|
||||
for (int i=0;i<compiler_args.size();i++) {
|
||||
argv.push_back(compiler_args[i].c_str());
|
||||
}
|
||||
argv.push_back(nullptr);
|
||||
execvp(compiler_path.c_str(),const_cast<char* const*>(argv.data()));
|
||||
print_deepness_vyld("ParallelVyldCompilation: An error happened while executing command.");
|
||||
_exit(1);
|
||||
} else {
|
||||
close(pipefd[1]);
|
||||
std::stringstream buffer;
|
||||
char c;
|
||||
while (read(pipefd[0],&c,1)>0) {
|
||||
buffer<<c;
|
||||
}
|
||||
close(pipefd[0]);
|
||||
int status;
|
||||
waitpid(pid,&status,0);
|
||||
if (!WIFEXITED(status)) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: An error happened in forked process.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (WEXITSTATUS(status)==0) {
|
||||
print_deepness_vyld("ParallelVyldCompilation: Command exited with error (status "+to_string(WEXITSTATUS(status))+"), showing output:\n");
|
||||
cout<<buffer.str()<<endl;
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
} else {
|
||||
return vybuild::actions::ActionStatus::Success;
|
||||
}
|
||||
}
|
||||
}
|
||||
return vybuild::actions::ActionStatus::Success;
|
||||
}
|
||||
vybuild::actions::ActionStatus parrallel_vyld_compilation_worker(size_t thread_num) {
|
||||
while (true) {
|
||||
function<vybuild::actions::ActionStatus()> task;
|
||||
{
|
||||
std::lock_guard lock(vyld_compilation_tasks_mutex);
|
||||
if (vyld_compilation_tasks.empty()) break;
|
||||
task=std::move(vyld_compilation_tasks.front());
|
||||
vyld_compilation_tasks.pop();
|
||||
}
|
||||
auto status=task();
|
||||
if (status!=vybuild::actions::ActionStatus::Success) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
return vybuild::actions::ActionStatus::Success;
|
||||
}
|
||||
vybuild::actions::ActionStatus vybuild::actions::VyldCompilationAction::run_action() {
|
||||
if (this->source_files_variables) this->source_files=vybuild::parser::vector_string_vars(this->source_files);
|
||||
if (this->source_files_path_completion) this->source_files=vybuild::parser::vector_string_path_completions(this->source_files,".c");
|
||||
if (this->source_asm_variables) this->source_asm=vybuild::parser::vector_string_vars(this->source_asm);
|
||||
if (this->source_asm_path_completion) this->source_asm=vybuild::parser::vector_string_path_completions(this->source_asm,".asm");
|
||||
if (this->compiler_variables) this->compiler=vybuild::parser::string_vars(this->compiler);
|
||||
if (this->assembler_variables) this->assembler=vybuild::parser::string_vars(this->assembler);
|
||||
if (this->linker_variables) this->linker=vybuild::parser::string_vars(this->linker);
|
||||
if (this->compiler_flags_variables) this->compiler_flags=vybuild::parser::string_vars(this->compiler_flags);
|
||||
if (this->output_file_variables) this->output_file=vybuild::parser::string_vars(this->output_file);
|
||||
if (this->headers_command_variables) this->headers_command=vybuild::parser::string_vars(this->headers_command);
|
||||
string compiler_path=find_executable_vyld(this->compiler);
|
||||
string compiler_hash="";
|
||||
auto vars_list=vybuild::vars::get_global_variables_list();
|
||||
if (this->object_files_cache_authorized) {
|
||||
ifstream compiler_bin(compiler_path,ios::binary);
|
||||
if (!compiler_bin) {
|
||||
print_deepness_vyld("VyldCompilationAction: Cannot open compiler binary: "+compiler_path);
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
size_t compiler_size=fs::file_size(compiler_path);
|
||||
vector<uint8_t> compiler_data(compiler_size);
|
||||
compiler_bin.read(reinterpret_cast<char*>(compiler_data.data()),compiler_size);
|
||||
if (!compiler_bin) {
|
||||
print_deepness_vyld("VyldCompilationAction: Cannot read compiler binary: "+compiler_path);
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
compiler_hash=vybuild::cache::xxhash_to_string(XXH3_128bits(compiler_data.data(),compiler_data.size()));
|
||||
for (auto &v:vars_list) {
|
||||
if (v.starts_with("\\$__VYBUILD_COMPILER_HASH_")) {
|
||||
compiler_hash+="\n"+get_command_output_vyld(vybuild::vars::get_global_variable(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
char buf[PATH_MAX];
|
||||
ssize_t len=readlink("/proc/self/exe",buf,sizeof(buf)-1);
|
||||
fs::path exe_path;
|
||||
if (len!=-1) {
|
||||
buf[len]='\0';
|
||||
exe_path=fs::path(buf);
|
||||
} else {
|
||||
print_deepness_vyld("VyldCompilationAction: Couldn't obtain vybuild executable path.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
exe_path=exe_path.parent_path();
|
||||
if (!fs::exists(exe_path/"_vyx_start.c")) {
|
||||
print_deepness_vyld("VyldCompilationAction: _vyx_start.c isn't accessible.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
this->source_files.insert(this->source_files.begin(),string(exe_path/"_vyx_start.c"));
|
||||
size_t nb_thread=thread::hardware_concurrency();
|
||||
size_t original_quantity=this->source_files.size();
|
||||
fs::path build_path=".vybuild_build";
|
||||
fs::create_directory(build_path);
|
||||
auto compiler_args=split_args_shell_vyld(this->compiler_flags+" -fno-pic -m64 -mcmodel=large");
|
||||
auto compiler_args_entry=split_args_shell_vyld("-ffreestanding -nostdlib -nostartfiles -Wall -Wextra -fno-stack-protector -Wno-missing-prototypes -fno-builtin -fno-pic -m64 -mcmodel=large");
|
||||
vector<string> outputs;
|
||||
for (int i=0;i<original_quantity;i++) {
|
||||
string source_file=std::move(this->source_files[i]);
|
||||
string filename=fs::path(source_file).filename().string();
|
||||
string output_file=build_path/(filename.substr(0,filename.size()-2)+".o");
|
||||
string dfile_path=build_path/(filename.substr(0,filename.size()-2)+".d");
|
||||
string headers_cmd=this->headers_command;
|
||||
outputs.push_back(output_file);
|
||||
if (source_file!=string(exe_path/"_vyx_start.c")) {
|
||||
vyld_compilation_tasks.push([source_file=std::move(source_file),compiler_path,compiler_hash,compiler_args,dfile_path=std::move(dfile_path),headers_cmd,output_file=std::move(output_file)]() mutable -> vybuild::actions::ActionStatus {
|
||||
return parallel_vyld_compilation(source_file,compiler_path,compiler_hash,compiler_args,dfile_path,headers_cmd,output_file);
|
||||
});
|
||||
} else {
|
||||
vyld_compilation_tasks.push([source_file=std::move(source_file),compiler_path,compiler_hash,compiler_args_entry,dfile_path=std::move(dfile_path),headers_cmd,output_file=std::move(output_file)]() mutable -> vybuild::actions::ActionStatus {
|
||||
return parallel_vyld_compilation(source_file,compiler_path,compiler_hash,compiler_args_entry,dfile_path,headers_cmd,output_file);
|
||||
});
|
||||
}
|
||||
}
|
||||
vector<thread> threads;
|
||||
vector<vybuild::actions::ActionStatus> results;
|
||||
mutex results_mutex;
|
||||
size_t real_threads=0;
|
||||
if (original_quantity>nb_thread) {
|
||||
real_threads=nb_thread;
|
||||
} else {
|
||||
real_threads=original_quantity;
|
||||
}
|
||||
results.resize(real_threads,vybuild::actions::ActionStatus::Success);
|
||||
for (size_t i=0;i<real_threads;i++) {
|
||||
threads.emplace_back([i,&results,&results_mutex]() {
|
||||
auto status=parrallel_vyld_compilation_worker(i);
|
||||
lock_guard<mutex> lock(results_mutex);
|
||||
results[i]=status;
|
||||
});
|
||||
}
|
||||
for (auto &t:threads) {
|
||||
t.join();
|
||||
}
|
||||
for (auto status:results) {
|
||||
if (status!=vybuild::actions::ActionStatus::Success) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
string assembler_path=find_executable_vyld(this->assembler);
|
||||
for (auto &f:this->source_asm) {
|
||||
string source_file=std::move(f);
|
||||
string filename=fs::path(source_file).filename().string();
|
||||
string output_file=build_path/(filename.substr(0,filename.size()-4)+".o");
|
||||
outputs.push_back(output_file);
|
||||
int pipefd[2];
|
||||
if (pipe(pipefd)==-1) {
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened while creating pipe.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
pid_t pid=fork();
|
||||
if (pid<0) {
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened while forking.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (pid==0) {
|
||||
close(pipefd[0]);
|
||||
dup2(pipefd[1],STDOUT_FILENO);
|
||||
dup2(pipefd[1],STDERR_FILENO);
|
||||
close(pipefd[1]);
|
||||
vector<string> all_args;
|
||||
all_args.push_back(assembler_path);
|
||||
all_args.push_back("-f");
|
||||
all_args.push_back("elf64");
|
||||
all_args.push_back(source_file);
|
||||
all_args.push_back("-o");
|
||||
all_args.push_back(output_file);
|
||||
std::vector<const char*> argv;
|
||||
for (auto &s:all_args) argv.push_back(s.c_str());
|
||||
argv.push_back(nullptr);
|
||||
execvp(assembler_path.c_str(),const_cast<char* const*>(argv.data()));
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened while executing command.");
|
||||
_exit(1);
|
||||
} else {
|
||||
close(pipefd[1]);
|
||||
std::stringstream buffer;
|
||||
char c;
|
||||
while (read(pipefd[0],&c,1)>0) {
|
||||
buffer<<c;
|
||||
}
|
||||
close(pipefd[0]);
|
||||
int status;
|
||||
waitpid(pid,&status,0);
|
||||
if (!WIFEXITED(status)) {
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened in forked process.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (WEXITSTATUS(status)!=0) {
|
||||
print_deepness_vyld("VyldCompilationAction: Command exited with error (status "+to_string(WEXITSTATUS(status))+"), showing output:\n");
|
||||
cout<<buffer.str()<<endl;
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
}
|
||||
}
|
||||
int pipefd[2];
|
||||
if (pipe(pipefd)==-1) {
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened while creating pipe.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
pid_t pid=fork();
|
||||
if (pid<0) {
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened while forking.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (pid==0) {
|
||||
close(pipefd[0]);
|
||||
dup2(pipefd[1],STDOUT_FILENO);
|
||||
dup2(pipefd[1],STDERR_FILENO);
|
||||
close(pipefd[1]);
|
||||
vector<string> all_args;
|
||||
all_args.push_back(compiler_path);
|
||||
all_args.push_back("-r");
|
||||
all_args.insert(all_args.end(),outputs.begin(),outputs.end());
|
||||
all_args.push_back("-o");
|
||||
all_args.push_back((build_path/"combined.o").string());
|
||||
std::vector<const char*> argv;
|
||||
for (auto &s:all_args) argv.push_back(s.c_str());
|
||||
argv.push_back(nullptr);
|
||||
execvp(compiler_path.c_str(),const_cast<char* const*>(argv.data()));
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened while executing command.");
|
||||
_exit(1);
|
||||
} else {
|
||||
close(pipefd[1]);
|
||||
std::stringstream buffer;
|
||||
char c;
|
||||
while (read(pipefd[0],&c,1)>0) {
|
||||
buffer<<c;
|
||||
}
|
||||
close(pipefd[0]);
|
||||
int status;
|
||||
waitpid(pid,&status,0);
|
||||
if (!WIFEXITED(status)) {
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened in forked process.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (WEXITSTATUS(status)!=0) {
|
||||
print_deepness_vyld("VyldCompilationAction: Command exited with error (status "+to_string(WEXITSTATUS(status))+"), showing output:\n");
|
||||
cout<<buffer.str()<<endl;
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
}
|
||||
ELFIO::elfio reader;
|
||||
fs::path combined_o=build_path/"combined.o";
|
||||
if (!reader.load(string(combined_o))) {
|
||||
print_deepness_vyld("VyldCompilationAction: couldn't open combined.o.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (reader.get_type()!=ELFIO::ET_REL) {
|
||||
print_deepness_vyld("VyldCompilationAction: combined.o isn't a relocatable object file.");
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
if (reader.get_class()!=ELFIO::ELFCLASS64) {
|
||||
print_deepness_vyld("VyldCompilationAction: combined.o isn't a 64-bit ELF file.");
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
if (reader.get_machine()!=ELFIO::EM_X86_64) {
|
||||
print_deepness_vyld("VyldCompilationAction: combined.o isn't a x86-64 file.");
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
const ELFIO::section* text_sec=reader.sections[".text"];
|
||||
const ELFIO::section* data_sec=reader.sections[".data"];
|
||||
const ELFIO::section* rodata_sec=reader.sections[".rodata"];
|
||||
const ELFIO::section* bss_sec=reader.sections[".bss"];
|
||||
if (!text_sec) {
|
||||
print_deepness_vyld("VyldCompilationAction: no .text section found.");
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
if (text_sec->get_size()==0) {
|
||||
print_deepness_vyld("VyldCompilationAction: .text is empty.");
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
size_t text_size=text_sec->get_size();
|
||||
size_t text_size_padded=pad_size(text_size,4096);
|
||||
size_t data_size=0;
|
||||
size_t data_size_padded=0;
|
||||
size_t rodata_size=0;
|
||||
size_t rodata_size_padded=0;
|
||||
size_t bss_size=0;
|
||||
size_t bss_size_padded=0;
|
||||
if (data_sec) {
|
||||
data_size=data_sec->get_size();
|
||||
data_size_padded=pad_size(data_size,4096);
|
||||
}
|
||||
if (rodata_sec) {
|
||||
rodata_size=rodata_sec->get_size();
|
||||
for (const auto &s:reader.sections) {
|
||||
if (s->get_name().size()>7 && s->get_name().substr(0,7)==".rodata" && s->get_name()!=".rodata") {
|
||||
rodata_size+=s->get_size();
|
||||
}
|
||||
}
|
||||
rodata_size_padded=pad_size(rodata_size,4096);
|
||||
}
|
||||
if (bss_sec) {
|
||||
bss_size=bss_sec->get_size();
|
||||
bss_size_padded=pad_size(bss_size,4096);
|
||||
}
|
||||
vyx_addresses va=generate_vyx_addresses();
|
||||
size_t text_offset=va.text_offset;
|
||||
size_t data_offset=text_offset+text_size_padded;
|
||||
size_t rodata_offset=data_offset+data_size_padded;
|
||||
size_t bss_offset=rodata_offset+rodata_size_padded;
|
||||
ofstream ld(build_path/"script.ld");
|
||||
ld<<"ENTRY(_vyx_start)\n";
|
||||
ld<<"MEMORY\n{\n";
|
||||
ld<<" TEXT (rx) : ORIGIN = 0x"<<hex<<text_offset<<", LENGTH = "<<dec<<text_size_padded<<"\n";
|
||||
ld<<" DATA (rw) : ORIGIN = 0x"<<hex<<data_offset<<", LENGTH = "<<dec<<data_size_padded<<"\n";
|
||||
ld<<" RODATA (r) : ORIGIN = 0x"<<hex<<rodata_offset<<", LENGTH = "<<dec<<rodata_size_padded<<"\n";
|
||||
ld<<" BSS (rw) : ORIGIN = 0x"<<hex<<bss_offset<<", LENGTH = "<<dec<<bss_size_padded<<"\n";
|
||||
ld<<"}\nSECTIONS\n{\n";
|
||||
ld<<" .text :\n";
|
||||
ld<<" {\n";
|
||||
ld<<" . = ORIGIN(TEXT);\n";
|
||||
ld<<" *(.text)\n";
|
||||
ld<<" *(.text.*)\n";
|
||||
ld<<" . = ALIGN(0x1000);\n";
|
||||
ld<<" } > TEXT\n\n";
|
||||
ld<<" .data :\n";
|
||||
ld<<" {\n";
|
||||
ld<<" . = ORIGIN(DATA);\n";
|
||||
ld<<" *(.data)\n";
|
||||
ld<<" *(.data.*)\n";
|
||||
ld<<" . = ALIGN(0x1000);\n";
|
||||
ld<<" } > DATA\n\n";
|
||||
ld<<" .rodata :\n";
|
||||
ld<<" {\n";
|
||||
ld<<" . = ORIGIN(RODATA);\n";
|
||||
ld<<" *(.rodata)\n";
|
||||
ld<<" *(.rodata.*)\n";
|
||||
ld<<" . = ALIGN(0x1000);\n";
|
||||
ld<<" } > RODATA\n\n";
|
||||
ld<<" .bss :\n";
|
||||
ld<<" {\n";
|
||||
ld<<" . = ORIGIN(BSS);\n";
|
||||
ld<<" *(.bss)\n";
|
||||
ld<<" *(.bss.*)\n";
|
||||
ld<<" . = ALIGN(0x1000);\n";
|
||||
ld<<" } > BSS\n\n";
|
||||
ld<<" /DISCARD/ :\n";
|
||||
ld<<" {\n";
|
||||
ld<<" *(.note.*)\n";
|
||||
ld<<" *(.comment)\n";
|
||||
ld<<" *(.eh_frame)\n";
|
||||
ld<<" *(.eh_frame_hdr)\n";
|
||||
ld<<" }\n}";
|
||||
ld.close();
|
||||
pipefd[0]=0;
|
||||
pipefd[1]=0;
|
||||
if (pipe(pipefd)==-1) {
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened while creating pipe.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
pid=fork();
|
||||
if (pid<0) {
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened while forking.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (pid==0) {
|
||||
close(pipefd[0]);
|
||||
dup2(pipefd[1],STDOUT_FILENO);
|
||||
dup2(pipefd[1],STDERR_FILENO);
|
||||
close(pipefd[1]);
|
||||
vector<string> all_args;
|
||||
all_args.push_back(this->linker);
|
||||
all_args.push_back("-T");
|
||||
all_args.push_back((build_path/"script.ld").string());
|
||||
all_args.push_back("-o");
|
||||
all_args.push_back((build_path/"compiled.elf").string());
|
||||
all_args.push_back((build_path/"combined.o").string());
|
||||
std::vector<const char*> argv;
|
||||
for (auto &s:all_args) argv.push_back(s.c_str());
|
||||
argv.push_back(nullptr);
|
||||
execvp(this->linker.c_str(),const_cast<char* const*>(argv.data()));
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened while executing command.");
|
||||
_exit(1);
|
||||
} else {
|
||||
close(pipefd[1]);
|
||||
std::stringstream buffer;
|
||||
char c;
|
||||
while (read(pipefd[0],&c,1)>0) {
|
||||
buffer<<c;
|
||||
}
|
||||
close(pipefd[0]);
|
||||
int status;
|
||||
waitpid(pid,&status,0);
|
||||
if (!WIFEXITED(status)) {
|
||||
print_deepness_vyld("VyldCompilationAction: An error happened in forked process.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (WEXITSTATUS(status)!=0) {
|
||||
print_deepness_vyld("VyldCompilationAction: Command exited with error (status "+to_string(WEXITSTATUS(status))+"), showing output:\n");
|
||||
cout<<buffer.str()<<endl;
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
}
|
||||
fs::path compiled_elf=build_path/"compiled.elf";
|
||||
if (!reader.load(string(compiled_elf))) {
|
||||
print_deepness_vyld("VyldCompilationAction: Couldn't open combined.elf.");
|
||||
return vybuild::actions::ActionStatus::SystemError;
|
||||
}
|
||||
if (reader.get_type()!=ELFIO::ET_EXEC) {
|
||||
print_deepness_vyld("VyldCompilationAction: compiled.elf isn't isn't an ELF binary.");
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
if (reader.get_class()!=ELFIO::ELFCLASS64) {
|
||||
print_deepness_vyld("VyldCompilationAction: combined.elf isn't a 64-bit ELF file.");
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
if (reader.get_machine()!=ELFIO::EM_X86_64) {
|
||||
print_deepness_vyld("VyldCompilationAction: combined.elf isn't a x86_64 file.");
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
const ELFIO::section* elf_text_sec=reader.sections[".text"];
|
||||
const ELFIO::section* elf_data_sec=reader.sections[".data"];
|
||||
const ELFIO::section* elf_rodata_sec=reader.sections[".rodata"];
|
||||
const ELFIO::section* elf_bss_sec=reader.sections[".bss"];
|
||||
if (!elf_text_sec) {
|
||||
print_deepness_vyld("VyldCompilationAction: no .text section found.");
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
if (elf_text_sec->get_size()==0) {
|
||||
print_deepness_vyld("VyldCompilationAction: .text is empty.");
|
||||
return vybuild::actions::ActionStatus::Fail;
|
||||
}
|
||||
vector<unsigned char> elf_text_bin(text_size_padded,0);
|
||||
vector<unsigned char> elf_data_bin(data_size_padded,0);
|
||||
vector<unsigned char> elf_rodata_bin(rodata_size_padded,0);
|
||||
memcpy(elf_text_bin.data(),elf_text_sec->get_data(),elf_text_sec->get_size());
|
||||
if (elf_data_sec->get_size()!=0) {
|
||||
memcpy(elf_data_bin.data(),elf_data_sec->get_data(),elf_data_sec->get_size());
|
||||
}
|
||||
if (elf_rodata_sec->get_size()!=0) {
|
||||
memcpy(elf_rodata_bin.data(),elf_rodata_sec->get_data(),elf_rodata_sec->get_size());
|
||||
}
|
||||
uint8_t vyx_sig[3]={'V','y','X'};
|
||||
uint16_t vyx_ver=VY_COMMON_VERSIONS_VYX;
|
||||
string outfile=this->output_file;
|
||||
size_t payload_count=this->payloads.size();
|
||||
auto payloads=generate_payloads(this->payloads);
|
||||
ofstream out(outfile,ios::binary);
|
||||
out.write(reinterpret_cast<char*>(vyx_sig),3);
|
||||
out.write(reinterpret_cast<char*>(&vyx_ver),2);
|
||||
out.write(reinterpret_cast<char*>(&va.text_offset),8);
|
||||
out.write(reinterpret_cast<char*>(&va.stack_base),8);
|
||||
out.write(reinterpret_cast<char*>(&text_size_padded),8);
|
||||
out.write(reinterpret_cast<char*>(&data_size_padded),8);
|
||||
out.write(reinterpret_cast<char*>(&rodata_size_padded),8);
|
||||
uint64_t bss_size_elf=elf_bss_sec->get_size();
|
||||
out.write(reinterpret_cast<char*>(&bss_size_elf),8);
|
||||
out.write(reinterpret_cast<char*>(&payload_count),8);
|
||||
out.write(reinterpret_cast<char*>(elf_text_bin.data()),elf_text_bin.size());
|
||||
if (data_size_padded!=0) out.write(reinterpret_cast<char*>(elf_data_bin.data()),elf_data_bin.size());
|
||||
if (rodata_size_padded!=0) out.write(reinterpret_cast<char*>(elf_rodata_bin.data()),elf_rodata_bin.size());
|
||||
if (payload_count!=0) {
|
||||
out.write(reinterpret_cast<char*>(payloads.data()),payloads.size());
|
||||
}
|
||||
out.close();
|
||||
fs::remove_all(build_path);
|
||||
return vybuild::actions::ActionStatus::Success;
|
||||
}
|
||||
44
vybuild/vybuild.cpp
Normal file
44
vybuild/vybuild.cpp
Normal file
@@ -0,0 +1,44 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "vybuild.hpp"
|
||||
#include <string>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
namespace fs=std::filesystem;
|
||||
int main(int argc,char** argv) {
|
||||
if (argc<2) {
|
||||
cout<<"[VyBuild] Error: not enough arguments."<<endl;
|
||||
return -1;
|
||||
}
|
||||
string root_module_path=string(argv[1]);
|
||||
if (!fs::exists(root_module_path)) {
|
||||
cout<<"[VyBuild] Error: provided file doesn't exist."<<endl;
|
||||
return -1;
|
||||
}
|
||||
bool smart_cache=true;
|
||||
int bumb=1;
|
||||
if (argc>2) {
|
||||
for (int i=2;i<argc;i++) {
|
||||
if (string(argv[i])=="--purge-cache") {
|
||||
fs::remove_all(".vybuild_cache");
|
||||
fs::remove_all(".vybuild_scache");
|
||||
continue;
|
||||
}
|
||||
if (string(argv[i])=="--disable-smart-cache") {
|
||||
smart_cache=false;
|
||||
continue;
|
||||
}
|
||||
if (string(argv[i])!="") {
|
||||
vybuild::vars::set_global_variable("%"+to_string(bumb)+"%",string(argv[i]));
|
||||
bumb++;
|
||||
}
|
||||
}
|
||||
}
|
||||
auto root_module=vybuild::module::Module(root_module_path,true);
|
||||
vybuild::vars::set_global_variable("%rootcallerfolder%",fs::absolute(fs::path(root_module_path)).parent_path().string());
|
||||
vybuild::cache::init_cache(smart_cache);
|
||||
cout<<"[VyBuild] Running first module: "+root_module.name<<endl;
|
||||
auto status=root_module.run_module(true,false);
|
||||
if (status==vybuild::actions::ActionStatus::Success) vybuild::cache::clean_cache();
|
||||
return 0;
|
||||
}
|
||||
1022
vybuild/vybuild.hpp
Normal file
1022
vybuild/vybuild.hpp
Normal file
File diff suppressed because it is too large
Load Diff
42
vybuild/xxhash.c
Normal file
42
vybuild/xxhash.c
Normal file
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* xxHash - Extremely Fast Hash algorithm
|
||||
* Copyright (C) 2012-2023 Yann Collet
|
||||
*
|
||||
* BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are
|
||||
* met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following disclaimer
|
||||
* in the documentation and/or other materials provided with the
|
||||
* distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* You can contact the author at:
|
||||
* - xxHash homepage: https://www.xxhash.com
|
||||
* - xxHash source repository: https://github.com/Cyan4973/xxHash
|
||||
*/
|
||||
|
||||
/*
|
||||
* xxhash.c instantiates functions defined in xxhash.h
|
||||
*/
|
||||
|
||||
#define XXH_STATIC_LINKING_ONLY /* access advanced declarations */
|
||||
#define XXH_IMPLEMENTATION /* access definitions */
|
||||
|
||||
#include "xxhash.h"
|
||||
7490
vybuild/xxhash.h
Normal file
7490
vybuild/xxhash.h
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user