From 64769c5d6f110be073d3144324b675c59530125a Mon Sep 17 00:00:00 2001 From: Peter Matula Date: Sat, 23 May 2020 20:43:05 +0200 Subject: [PATCH] Optimize utils and file parsing to prevent timeouts in exotic files (#772) * utils: optimize replaceNonprintableChars() It turns out it can be used quite often in fileformat. * utils/system: replace custom sleep() with std::this_thread::sleep_for() * utils/test.h: remove, not used anywhere * utils/file_i: break long lines * utils/dynamic_buffer: break long lines * utils/const: remove, not used anywhere * utils/alignment: break long lines * utils/byte_value_storage: break long lines * utils/conversion: replace toString(0 with std::to_string() * utils/conversion: remove unused functions * utils/conversion: reduce usage of numToStr() * progress * utils/conversion: refactor hex-string conversions * fileformat: optimize PeFormat::scanForSectionAnomalies() * pelib/ImportDirectory: add guard against infinite cycle * capstone2llvmirtool: fix compilation, add std:: namespace --- .../fileformat/file_format/pe/pe_format.h | 2 +- include/retdec/pelib/ImportDirectory.h | 9 +- include/retdec/utils/alignment.h | 6 +- include/retdec/utils/byte_value_storage.h | 226 +++++++++++--- include/retdec/utils/const.h | 73 ----- include/retdec/utils/conversion.h | 292 ++++++++---------- include/retdec/utils/dynamic_buffer.h | 103 ++++-- include/retdec/utils/file_io.h | 68 ++-- include/retdec/utils/string.h | 4 - include/retdec/utils/system.h | 2 - include/retdec/utils/test.h | 21 -- src/ar-extractor/archive_wrapper.cpp | 4 +- src/capstone2llvmirtool/capstone2llvmir.cpp | 70 +++-- src/common/address.cpp | 7 +- src/common/function.cpp | 3 - src/cpdetect/heuristics/heuristics.cpp | 2 +- src/cpdetect/heuristics/pe_heuristics.cpp | 10 +- src/fileformat/file_format/elf/elf_format.cpp | 2 +- .../file_format/macho/macho_format.cpp | 2 +- src/fileformat/file_format/pe/pe_format.cpp | 108 +++++-- .../types/certificate_table/certificate.cpp | 6 +- .../types/dotnet_types/dotnet_class.cpp | 2 +- .../types/dotnet_types/dotnet_data_types.cpp | 4 +- .../types/export_table/export_table.cpp | 5 +- .../types/import_table/import_table.cpp | 6 +- .../relocation_table/relocation_table.cpp | 2 +- .../types/resource_table/resource_table.cpp | 14 +- .../types/symbol_table/macho_symbol.cpp | 2 +- .../types/symbol_table/symbol_table.cpp | 6 +- src/fileformat/utils/asn1.cpp | 6 +- src/fileformat/utils/other.cpp | 4 +- src/fileinfo/file_detector/coff_detector.cpp | 2 +- src/fileinfo/file_detector/elf_detector.cpp | 12 +- src/fileinfo/file_detector/macho_detector.cpp | 4 +- .../file_information_types/type_conversions.h | 15 +- .../anomalies_plain_getter.cpp | 4 +- .../data_directory_plain_getter.cpp | 4 +- .../dynamic_sections_plain_getter.cpp | 2 +- .../elf_auxv_plain_getter.cpp | 6 +- .../elf_core_map_plain_getter.cpp | 6 +- .../elf_notes_plain_getter.cpp | 14 +- .../export_table_plain_getter.cpp | 4 +- .../import_table_plain_getter.cpp | 4 +- .../missing_deps_plain_getter.cpp | 4 +- .../pattern_matches_plain_getter.cpp | 8 +- .../relocation_tables_plain_getter.cpp | 2 +- .../resource_plain_getter.cpp | 4 +- .../rich_header_plain_getter.cpp | 4 +- .../section_plain_getter.cpp | 2 +- .../strings_plain_getter.cpp | 4 +- .../tls_info_plain_getter.cpp | 4 +- .../typeref_table_plain_getter.cpp | 4 +- ...rsion_info_language_table_plain_getter.cpp | 4 +- ...version_info_string_table_plain_getter.cpp | 4 +- ...visual_basic_extern_table_plain_getter.cpp | 4 +- .../certificate_table_plain_getter.cpp | 6 +- .../anomalies_json_getter.cpp | 4 +- .../data_directory_json_getter.cpp | 4 +- .../dynamic_sections_json_getter.cpp | 2 +- .../export_table_json_getter.cpp | 4 +- .../import_table_json_getter.cpp | 4 +- .../missing_deps_json_getter.cpp | 2 +- .../relocation_tables_json_getter.cpp | 2 +- .../resource_json_getter.cpp | 4 +- .../rich_header_json_getter.cpp | 4 +- .../section_json_getter.cpp | 2 +- .../strings_json_getter.cpp | 4 +- .../typeref_table_json_getter.cpp | 4 +- .../file_presentation/json_presentation.cpp | 10 +- src/fileinfo/file_wrapper/pe/pe_wrapper.cpp | 2 +- src/getsig/getsig.cpp | 2 +- src/idr2pat/idr2pat.cpp | 2 +- src/llvmir2hll/graphs/cfg/cfg.cpp | 1 - src/llvmir2hll/graphs/cfg/cfg_writer.cpp | 2 - .../cfg/cfg_writers/graphviz_cfg_writer.cpp | 5 +- .../cg/cg_writers/graphviz_cg_writer.cpp | 2 - src/llvmir2hll/hll/hll_writer.cpp | 4 +- .../hll/hll_writers/c_hll_writer.cpp | 5 +- src/llvmir2hll/ir/statement.cpp | 2 - .../optimizer/optimizer_manager.cpp | 6 +- src/llvmir2hll/utils/graphviz.cpp | 3 +- src/llvmir2hll/utils/string.cpp | 3 +- src/llvmir2hll/var_renamer/var_renamer.cpp | 3 +- .../var_renamers/readable_var_renamer.cpp | 3 +- .../types/symbol_pattern.cpp | 2 +- src/utils/alignment.cpp | 23 +- src/utils/byte_value_storage.cpp | 271 ++++++++++++---- src/utils/conversion.cpp | 220 +++---------- src/utils/dynamic_buffer.cpp | 71 +++-- src/utils/string.cpp | 31 +- src/utils/system.cpp | 19 -- tests/utils/CMakeLists.txt | 1 - tests/utils/const_tests.cpp | 59 ---- tests/utils/conversion_tests.cpp | 176 ++--------- tests/utils/string_tests.cpp | 10 - 95 files changed, 1071 insertions(+), 1109 deletions(-) delete mode 100644 include/retdec/utils/const.h delete mode 100644 include/retdec/utils/test.h delete mode 100644 tests/utils/const_tests.cpp diff --git a/include/retdec/fileformat/file_format/pe/pe_format.h b/include/retdec/fileformat/file_format/pe/pe_format.h index af0aae728..08f101b95 100644 --- a/include/retdec/fileformat/file_format/pe/pe_format.h +++ b/include/retdec/fileformat/file_format/pe/pe_format.h @@ -116,7 +116,7 @@ class PeFormat : public FileFormat /// @} /// @name Auxiliary scanning methods /// @{ - void scanForSectionAnomalies(); + void scanForSectionAnomalies(unsigned anamaliesLimit = 1000); void scanForResourceAnomalies(); void scanForImportAnomalies(); void scanForExportAnomalies(); diff --git a/include/retdec/pelib/ImportDirectory.h b/include/retdec/pelib/ImportDirectory.h index 936ae30e5..f238c8314 100644 --- a/include/retdec/pelib/ImportDirectory.h +++ b/include/retdec/pelib/ImportDirectory.h @@ -13,6 +13,8 @@ #ifndef IMPORTDIRECTORY_H #define IMPORTDIRECTORY_H +#include + #include "retdec/pelib/PeLibAux.h" #include "retdec/pelib/PeHeader.h" @@ -699,6 +701,7 @@ namespace PeLib } // FirstThunk - IAT + std::set seenOffsets; for (unsigned int i=0;i tdCurr; inStream_w.clear(); diff --git a/include/retdec/utils/alignment.h b/include/retdec/utils/alignment.h index 292e33a35..cd52eedea 100644 --- a/include/retdec/utils/alignment.h +++ b/include/retdec/utils/alignment.h @@ -12,7 +12,11 @@ namespace retdec { namespace utils { -bool isAligned(std::uint64_t value, std::uint64_t alignment, std::uint64_t& remainder); +bool isAligned( + std::uint64_t value, + std::uint64_t alignment, + std::uint64_t& remainder); + std::uint64_t alignDown(std::uint64_t value, std::uint64_t alignment); std::uint64_t alignUp(std::uint64_t value, std::uint64_t alignment); diff --git a/include/retdec/utils/byte_value_storage.h b/include/retdec/utils/byte_value_storage.h index 82d6ec298..94e945c97 100644 --- a/include/retdec/utils/byte_value_storage.h +++ b/include/retdec/utils/byte_value_storage.h @@ -38,11 +38,24 @@ class ByteValueStorage virtual std::size_t getNumberOfNibblesInByte() const = 0; virtual bool hasMixedEndianForDouble() const = 0; - virtual bool getXByte(std::uint64_t address, std::uint64_t x, std::uint64_t& res, Endianness e = Endianness::UNKNOWN) const = 0; - virtual bool getXBytes(std::uint64_t address, std::uint64_t x, std::vector& res) const = 0; - - virtual bool setXByte(std::uint64_t address, std::uint64_t x, std::uint64_t val, Endianness e = Endianness::UNKNOWN) = 0; - virtual bool setXBytes(std::uint64_t address, const std::vector& val) = 0; + virtual bool getXByte( + std::uint64_t address, + std::uint64_t x, + std::uint64_t& res, + Endianness e = Endianness::UNKNOWN) const = 0; + virtual bool getXBytes( + std::uint64_t address, + std::uint64_t x, + std::vector& res) const = 0; + + virtual bool setXByte( + std::uint64_t address, + std::uint64_t x, + std::uint64_t val, + Endianness e = Endianness::UNKNOWN) = 0; + virtual bool setXBytes( + std::uint64_t address, + const std::vector& val) = 0; Endianness getInverseEndianness() const; bool isLittleEndian() const; @@ -56,51 +69,168 @@ class ByteValueStorage bool bitsToBig(std::vector& values) const; bool bitsToLittle(std::vector& values) const; - bool get1Byte(std::uint64_t address, std::uint64_t& res, Endianness e = Endianness::UNKNOWN) const; - bool get2Byte(std::uint64_t address, std::uint64_t& res, Endianness e = Endianness::UNKNOWN) const; - bool get4Byte(std::uint64_t address, std::uint64_t& res, Endianness e = Endianness::UNKNOWN) const; - bool get8Byte(std::uint64_t address, std::uint64_t& res, Endianness e = Endianness::UNKNOWN) const; - bool get10Byte(std::uint64_t address, long double& res) const; - bool getWord(std::uint64_t address, std::uint64_t& res, Endianness e = Endianness::UNKNOWN) const; - bool getFloat(std::uint64_t address, float& res) const; - bool getDouble(std::uint64_t address, double& res) const; - - bool set1Byte(std::uint64_t address, std::uint64_t val, Endianness e = Endianness::UNKNOWN); - bool set2Byte(std::uint64_t address, std::uint64_t val, Endianness e = Endianness::UNKNOWN); - bool set4Byte(std::uint64_t address, std::uint64_t val, Endianness e = Endianness::UNKNOWN); - bool set8Byte(std::uint64_t address, std::uint64_t val, Endianness e = Endianness::UNKNOWN); - bool set10Byte(std::uint64_t address, long double val); - bool setWord(std::uint64_t address, std::uint64_t val, Endianness e = Endianness::UNKNOWN); - bool setFloat(std::uint64_t address, float val); - bool setDouble(std::uint64_t address, double val); - - bool getXByteArray(std::uint64_t address, std::uint64_t x, std::vector& res, std::size_t size, Endianness e = Endianness::UNKNOWN) const; - bool get1ByteArray(std::uint64_t address, std::vector& res, std::size_t size, Endianness e = Endianness::UNKNOWN) const; - bool get2ByteArray(std::uint64_t address, std::vector& res, std::size_t size, Endianness e = Endianness::UNKNOWN) const; - bool get4ByteArray(std::uint64_t address, std::vector& res, std::size_t size, Endianness e = Endianness::UNKNOWN) const; - bool get8ByteArray(std::uint64_t address, std::vector& res, std::size_t size, Endianness e = Endianness::UNKNOWN) const; - bool get10ByteArray(std::uint64_t address, std::vector& res, std::size_t size) const; - bool getWordArray(std::uint64_t address, std::vector& res, std::size_t, Endianness e = Endianness::UNKNOWN) const; - bool getFloatArray(std::uint64_t address, std::vector& res, std::size_t size) const; - bool getDoubleArray(std::uint64_t address, std::vector& res, std::size_t size) const; - - bool getNTBS(std::uint64_t address, std::string& res, std::size_t size = 0) const; - bool getNTWS(std::uint64_t address, std::size_t width, std::vector& res) const; - bool getNTWSNice(std::uint64_t address, std::size_t width, std::vector& res) const; + bool get1Byte( + std::uint64_t address, + std::uint64_t& res, + Endianness e = Endianness::UNKNOWN) const; + bool get2Byte( + std::uint64_t address, + std::uint64_t& res, + Endianness e = Endianness::UNKNOWN) const; + bool get4Byte( + std::uint64_t address, + std::uint64_t& res, + Endianness e = Endianness::UNKNOWN) const; + bool get8Byte( + std::uint64_t address, + std::uint64_t& res, + Endianness e = Endianness::UNKNOWN) const; + bool get10Byte( + std::uint64_t address, + long double& res) const; + bool getWord( + std::uint64_t address, + std::uint64_t& res, + Endianness e = Endianness::UNKNOWN) const; + bool getFloat( + std::uint64_t address, + float& res) const; + bool getDouble( + std::uint64_t address, + double& res) const; + + bool set1Byte( + std::uint64_t address, + std::uint64_t val, + Endianness e = Endianness::UNKNOWN); + bool set2Byte( + std::uint64_t address, + std::uint64_t val, + Endianness e = Endianness::UNKNOWN); + bool set4Byte( + std::uint64_t address, + std::uint64_t val, + Endianness e = Endianness::UNKNOWN); + bool set8Byte( + std::uint64_t address, + std::uint64_t val, + Endianness e = Endianness::UNKNOWN); + bool set10Byte( + std::uint64_t address, + long double val); + bool setWord( + std::uint64_t address, + std::uint64_t val, + Endianness e = Endianness::UNKNOWN); + bool setFloat( + std::uint64_t address, + float val); + bool setDouble( + std::uint64_t address, + double val); + + bool getXByteArray( + std::uint64_t address, + std::uint64_t x, + std::vector& res, + std::size_t size, + Endianness e = Endianness::UNKNOWN) const; + bool get1ByteArray( + std::uint64_t address, + std::vector& res, + std::size_t size, + Endianness e = Endianness::UNKNOWN) const; + bool get2ByteArray( + std::uint64_t address, + std::vector& res, + std::size_t size, + Endianness e = Endianness::UNKNOWN) const; + bool get4ByteArray( + std::uint64_t address, + std::vector& res, + std::size_t size, + Endianness e = Endianness::UNKNOWN) const; + bool get8ByteArray( + std::uint64_t address, + std::vector& res, + std::size_t size, + Endianness e = Endianness::UNKNOWN) const; + bool get10ByteArray( + std::uint64_t address, + std::vector& res, + std::size_t size) const; + bool getWordArray( + std::uint64_t address, + std::vector& res, + std::size_t, + Endianness e = Endianness::UNKNOWN) const; + bool getFloatArray( + std::uint64_t address, + std::vector& res, std::size_t size) const; + bool getDoubleArray( + std::uint64_t address, + std::vector& res, std::size_t size) const; + + bool getNTBS( + std::uint64_t address, + std::string& res, + std::size_t size = 0) const; + bool getNTWS( + std::uint64_t address, + std::size_t width, + std::vector& res) const; + bool getNTWSNice( + std::uint64_t address, + std::size_t width, + std::vector& res) const; protected: - bool createValueFromBytes(const std::vector& data, std::uint64_t& value, Endianness endian, std::uint64_t offset = 0, std::uint64_t size = 0) const; - bool createBytesFromValue(std::uint64_t data, std::uint64_t x, std::vector& value, Endianness endian) const; - - bool get10ByteImpl(const std::vector& data, long double& res) const; - bool getFloatImpl(const std::vector& data, float& res) const; - bool getDoubleImpl(const std::vector& data, double& res) const; - - using GetNByteFn = std::function; - using GetXByteFn = std::function; - bool getNTBSImpl(const GetNByteFn& get1ByteFn, std::uint64_t address, std::string& res, std::size_t size) const; - bool getNTWSImpl(const GetXByteFn& getXByteFn, std::uint64_t address, std::size_t width, std::vector& res) const; - bool getNTWSNiceImpl(const GetXByteFn& getXByteFn, std::uint64_t address, std::size_t width, std::vector& res) const; + bool createValueFromBytes( + const std::vector& data, + std::uint64_t& value, + Endianness endian, + std::uint64_t offset = 0, + std::uint64_t size = 0) const; + bool createBytesFromValue( + std::uint64_t data, + std::uint64_t x, + std::vector& value, + Endianness endian) const; + + bool get10ByteImpl( + const std::vector& data, + long double& res) const; + bool getFloatImpl( + const std::vector& data, + float& res) const; + bool getDoubleImpl( + const std::vector& data, + double& res) const; + + using GetNByteFn = std::function; + using GetXByteFn = std::function; + + bool getNTBSImpl( + const GetNByteFn& get1ByteFn, + std::uint64_t address, + std::string& res, + std::size_t size) const; + bool getNTWSImpl( + const GetXByteFn& getXByteFn, + std::uint64_t address, + std::size_t width, + std::vector& res) const; + bool getNTWSNiceImpl( + const GetXByteFn& getXByteFn, + std::uint64_t address, + std::size_t width, + std::vector& res) const; }; } // namespace utils diff --git a/include/retdec/utils/const.h b/include/retdec/utils/const.h deleted file mode 100644 index 31b248591..000000000 --- a/include/retdec/utils/const.h +++ /dev/null @@ -1,73 +0,0 @@ -/** -* @file include/retdec/utils/const.h -* @brief A helper function to prevent code duplication between const and -* non-const member functions. -* @copyright (c) 2017 Avast Software, licensed under the MIT license -* -* The implementation is based on http://stackoverflow.com/a/16780327/2580955. -*/ - -#ifndef RETDEC_UTILS_CONST_H -#define RETDEC_UTILS_CONST_H - -namespace retdec { -namespace utils { - -// Internal helpers to remove constness. -// (std::remove_cv cannot be used here because we are removing the constness -// from the pointed/referenced type.) - -template -struct NonConst { using type = T; }; - -template -struct NonConst { using type = T; }; // by value - -template -struct NonConst { using type = T&; }; // by reference - -template -struct NonConst { using type = T*; }; // by pointer - -template -struct NonConst { using type = T&&; }; // by rvalue-reference - -/* -* @brief A helper function to prevent code duplication between const and -* non-const member functions. -* -* Usage example: -* @code -* class Array { -* public: -* // const version -* const int *getElement(std::size_t i) const { -* // Here comes the implementation. -* // ... -* } -* -* // non-const version -* int *getElement(std::size_t i) { -* return likeConstVersion(this, &Array::getElement, i); -* } -* -* // ... -* }; -* @endcode -*/ -template -auto likeConstVersion( - const Object *object, - ConstReturn (Object::*memFun)(MemFunArgs...) const, - RealArgs... args) -{ - return const_cast::type>( - (object->*memFun)(args...) - ); -} - -} // namespace utils -} // namespace retdec - -#endif diff --git a/include/retdec/utils/conversion.h b/include/retdec/utils/conversion.h index 8c2109586..371e8c91b 100644 --- a/include/retdec/utils/conversion.h +++ b/include/retdec/utils/conversion.h @@ -21,55 +21,139 @@ namespace utils { /// @name Conversions /// @{ -std::string toHex(std::uint64_t i, bool addBase = false, unsigned fillToN = 0); +char* byteToHexString(uint8_t b, bool uppercase = true); /** -* @brief Converts the given value into a string. -* -* @tparam T Type of @a value. -*/ -template -inline std::string toString(const T &value) { - std::ostringstream out; - out << value; - return out.str(); -} + * Converts the given array of numbers into a hexadecimal string representation + * @param data Array to be converted into a hexadecimal string + * @param dataSize Size of array + * @param result Into this parameter the result is stored + * @param offset First byte from @a data which will be converted + * @param size Number of bytes from @a data for conversion + * (0 means all bytes from @a offset) + * @param uppercase @c true if hex letters (A-F) should be uppercase + * @param spacing insert ' ' between every byte + */ +template void bytesToHexString( + const N *data, + std::size_t dataSize, + std::string &result, + std::size_t offset = 0, + std::size_t size = 0, + bool uppercase = true, + bool spacing = false) +{ + if (data == nullptr || offset >= dataSize) + { + return; + } -// Specialization for bool -template<> -inline std::string toString(const bool &value) { - std::ostringstream out; - out << std::boolalpha << value; - return out.str(); -} + size = (size == 0 || offset + size > dataSize) + ? dataSize - offset + : size; -// Specialization for float -template<> -inline std::string toString(const float &value) { - const int sigDigits = std::numeric_limits::digits10; - std::ostringstream out; - out << std::setprecision(sigDigits) << value; - return out.str(); + std::size_t hexIndex = 0; + + std::size_t sz = spacing ? (size * 3 - 1) : (size * 2); + result.resize(sz); + + for (std::size_t i = 0; i < size; ++i) + { + if (spacing && hexIndex > 0) + { + result[hexIndex++] = ' '; + } + auto res = byteToHexString(data[offset + i], uppercase); + result[hexIndex++] = res[0]; + result[hexIndex++] = res[1]; + } } -// Specialization for double -template<> -inline std::string toString(const double &value) { - const int sigDigits = std::numeric_limits::digits10; - std::ostringstream out; - out << std::setprecision(sigDigits) << value; - return out.str(); +/** + * Converts the given vector of numbers into a hexadecimal string representation + * @param bytes Vector to be converted into a hexadecimal string + * @param result Into this parameter the result is stored + * @param offset First byte from @a bytes which will be converted + * @param size Number of bytes from @a bytes for conversion + * (0 means all bytes from @a offset) + * @param uppercase @c true if hex letters (A-F) should be uppercase + * @param spacing insert ' ' between every byte + */ +template void bytesToHexString( + const std::vector &bytes, + std::string &result, + std::size_t offset = 0, + std::size_t size = 0, + bool uppercase = true, + bool spacing = false) +{ + bytesToHexString( + bytes.data(), + bytes.size(), + result, + offset, + size, + uppercase, + spacing + ); } -// Specialization for long double -template<> -inline std::string toString(const long double &value) { - const int sigDigits = std::numeric_limits::digits10; - std::ostringstream out; - out << std::setprecision(sigDigits) << value; - return out.str(); +/** +* @brief Converts the given integer into its hexadecimal representation. +* +* @param[in] w Number to be converted. +* @param[in] addBase Prepends "0x" before the result. +* @param[in] fillToN If needed, prepends "0" before the result to get at least +* @c fillToN characters long string. +* +* All letters in the result are lowercase. +*/ +template +std::string intToHexString(I w, bool addBase = false, unsigned fillToN = 0) +{ + static const char* digits = "0123456789abcdef"; + + size_t hex_len = sizeof(I)<<1; + + std::string rc(hex_len,'0'); + for (size_t i = 0, j = (hex_len-1)*4 ; i < hex_len; ++i, j -= 4) + { + rc[i] = digits[(w>>j) & 0x0f]; + } + + bool started = false; + std::string res; + size_t j = 0; + if (addBase) + { + res.resize(rc.size() + 2); + res[0] = '0'; + res[1] = 'x'; + j = 2; + } + else + { + res.resize(rc.size()); + } + for (size_t i = 0; i < rc.size(); ++i) + { + if (started) + { + res[j++] = rc[i]; + } + else if (rc[i] != '0' || (rc.size() - i <= fillToN) || (i == rc.size() - 1)) + { + res[j++] = rc[i]; + started = true; + } + } + res.resize(j); + + return res; } +std::vector hexStringToBytes(const std::string& hexIn); + /** * @brief Converts the given string into a number. * @@ -101,22 +185,6 @@ inline bool strToNum(const std::string &str, N &number, return true; } -/** -* @brief Converts the given number into a string. -* -* @param[in] number Number for conversion. -* @param[in] format String format (e.g. std::dec, std::hex). -* -* @return Resulting string. -*/ -template -inline std::string numToStr(const N number, - std::ios_base &(* format)(std::ios_base &) = std::dec) { - std::ostringstream strStream; - strStream << format << number; - return strStream.str(); -} - namespace { const std::size_t BITS_IN_BYTE = 8; @@ -162,91 +230,6 @@ template std::string bytesToBits(const std::vector &bytes) { return bytesToBits(bytes.data(), bytes.size()); } - -/** - * @brief Converts the given number into a bits. - * - * @param[in] byte Number to be converted into a bits. - * - * @return Resulting string. - */ -template -std::string byteToBits(N byte) { - std::vector vect(1, byte); - return bytesToBits(vect); -} - -/** - * Converts the single byte into a hexadecimal string representation - * @param oStr Output stream - * @param byte Data to be converted - * @param uppercase @c true if hex letters (A-F) should be uppercase - */ -template void byteToHexString(std::ostream& oStr, N byte, bool uppercase = true) -{ - oStr << std::hex << std::setfill('0') << std::setw(2) << (uppercase ? std::uppercase : std::nouppercase) << (byte & 0xFF); -} - -/** - * Converts the given array of numbers into a hexadecimal string representation - * @param data Array to be converted into a hexadecimal string - * @param dataSize Size of array - * @param result Into this parameter the result is stored - * @param offset First byte from @a data which will be converted - * @param size Number of bytes from @a data for conversion - * (0 means all bytes from @a offset) - * @param uppercase @c true if hex letters (A-F) should be uppercase - */ -template void bytesToHexString(const N *data, std::size_t dataSize, std::string &result, std::size_t offset = 0, std::size_t size = 0, bool uppercase = true) -{ - if(!data) - { - dataSize = 0; - } - - if(offset >= dataSize) - { - size = 0; - } - else - { - size = (size == 0 || offset + size > dataSize) ? dataSize - offset : size; - } - - // Sample: 4A2A008CF1AEE9BA49D8D1DAA22D8E868365ACE633823D464478239F27ED4F18 - // Tool: redec-fileinfo.exe, Debug, x64, data = image, dataSize = 0xE1BC00 - // Optimized: This code now takes 0.106 seconds to convert (measured in VS 2015 IDE) - // (down from about 40 seconds) - const char * intToHex = uppercase ? "0123456789ABCDEF" : "0123456789abcdef"; - std::size_t hexIndex = 0; - - // Reserve the necessary space for the hexa string - result.resize(size * 2); - - // Convert to hexa byte-by-byte. No reallocations - for (std::size_t i = 0; i < size; ++i, hexIndex += 2) - { - std::uint8_t oneByte = data[offset + i]; - - result[hexIndex + 0] = intToHex[(oneByte >> 0x04) & 0x0F]; - result[hexIndex + 1] = intToHex[(oneByte >> 0x00) & 0x0F]; - } -} - -/** - * Converts the given vector of numbers into a hexadecimal string representation - * @param bytes Vector to be converted into a hexadecimal string - * @param result Into this parameter the result is stored - * @param offset First byte from @a bytes which will be converted - * @param size Number of bytes from @a bytes for conversion - * (0 means all bytes from @a offset) - * @param uppercase @c true if hex letters (A-F) should be uppercase - */ -template void bytesToHexString(const std::vector &bytes, std::string &result, std::size_t offset = 0, std::size_t size = 0, bool uppercase = true) -{ - bytesToHexString(bytes.data(), bytes.size(), result, offset, size, uppercase); -} - /** * Converts the given array of numbers into a string * @param data Array to be converted into a string @@ -256,7 +239,12 @@ template void bytesToHexString(const std::vector &bytes, std::str * @param size Number of bytes from @a data for conversion * (0 means all bytes from @a offset) */ -template void bytesToString(const N *data, std::size_t dataSize, std::string &result, std::size_t offset = 0, std::size_t size = 0) +template void bytesToString( + const N *data, + std::size_t dataSize, + std::string &result, + std::size_t offset = 0, + std::size_t size = 0) { if(!data) { @@ -269,7 +257,9 @@ template void bytesToString(const N *data, std::size_t dataSize, std } else { - size = (size == 0 || offset + size > dataSize) ? dataSize - offset : size; + size = (size == 0 || offset + size > dataSize) + ? dataSize - offset + : size; } result.clear(); @@ -285,16 +275,15 @@ template void bytesToString(const N *data, std::size_t dataSize, std * @param size Number of bytes from @a bytes for conversion * (0 means all bytes from @a offset) */ -template void bytesToString(const std::vector &bytes, std::string &result, std::size_t offset = 0, std::size_t size = 0) +template void bytesToString( + const std::vector &bytes, + std::string &result, + std::size_t offset = 0, + std::size_t size = 0) { bytesToString(bytes.data(), bytes.size(), result, offset, size); } -unsigned long byteToULong8(const char *sByte, bool switchBitsOrder); -unsigned long byteToULongVariable(const char *sByte, std::size_t iByteSize); -unsigned long byteToULong(const char *sByte, std::size_t iByteSize, - bool switchBitsOrder = false); - void double10ToDouble8(std::vector &dest, const std::vector &src); @@ -303,13 +292,6 @@ unsigned int byteSwap32(unsigned int val); std::string byteSwap16(const std::string &val); std::string byteSwap32(const std::string &val); -std::string unsignedToBinString(unsigned long long int nValue, int nLength); -unsigned long long int binStringToUnsigned(const char *sValue); -long long int binStringToSigned(const char *sValue); - -std::vector hexStringToBytes(const std::string& hexIn); -std::string bytesToHexString(const std::vector& bytes); - /// @} } // namespace utils diff --git a/include/retdec/utils/dynamic_buffer.h b/include/retdec/utils/dynamic_buffer.h index c5e0a07be..00cdcfbfc 100644 --- a/include/retdec/utils/dynamic_buffer.h +++ b/include/retdec/utils/dynamic_buffer.h @@ -18,23 +18,43 @@ namespace retdec { namespace utils { /** - * @brief The class for dynamic buffered data manipulation taking the endianness of the data in account. + * @brief The class for dynamic buffered data manipulation taking the + * endianness of the data in account. * - * This class provides the wrapper around the vector of bytes. It allows to specify the endianness of the data. - * The data can be read from or written to this buffer using templated methods allowing not only per-byte manipulation, - * but also reading and writing of words, double words etc. The buffer has its initial capacity allowing it to grow into - * specified size. If the read or write requests the data from position that still falls into the capacity, the buffer resizes itself - * to this size dynamically. It also checks for out-of-bounds accesses. In case of reading it reads the bytes that would be - * out-of-bounds as 0 bytes and for writing it simply ignores the data that would be out-of-bounds. + * This class provides the wrapper around the vector of bytes. It allows to + * specify the endianness of the data. The data can be read from or written to + * this buffer using templated methods allowing not only per-byte manipulation, + * but also reading and writing of words, double words etc. The buffer has its + * initial capacity allowing it to grow into specified size. If the read or + * write requests the data from position that still falls into the capacity, + * the buffer resizes itself to this size dynamically. It also checks for + * out-of-bounds accesses. In case of reading it reads the bytes that would be + * out-of-bounds as 0 bytes and for writing it simply ignores the data that + * would be out-of-bounds. */ class DynamicBuffer { public: - DynamicBuffer(retdec::utils::Endianness endianness = retdec::utils::Endianness::LITTLE); - DynamicBuffer(uint32_t capacity, retdec::utils::Endianness endianness = retdec::utils::Endianness::LITTLE); - DynamicBuffer(const std::vector& data, retdec::utils::Endianness endianness = retdec::utils::Endianness::LITTLE); + DynamicBuffer( + retdec::utils::Endianness endianness + = retdec::utils::Endianness::LITTLE + ); + DynamicBuffer( + uint32_t capacity, + retdec::utils::Endianness endianness + = retdec::utils::Endianness::LITTLE + ); + DynamicBuffer( + const std::vector& data, + retdec::utils::Endianness endianness + = retdec::utils::Endianness::LITTLE + ); DynamicBuffer(const DynamicBuffer& dynamicBuffer); - DynamicBuffer(const DynamicBuffer& dynamicBuffer, uint32_t startPos, uint32_t amount); + DynamicBuffer( + const DynamicBuffer& dynamicBuffer, + uint32_t startPos, + uint32_t amount + ); DynamicBuffer& operator =(DynamicBuffer dynamicBuffer); @@ -55,22 +75,32 @@ class DynamicBuffer void forEachReverse(const std::function& func); /** - * Reads the data from the buffer. If the reading position is beyond the size of the real data, the real data are resized so this - * value can be read filling the new bytes with default (0) value. If the read overlaps the capacity of the buffer, only the bytes - * that still fall into the capacity are read and the rest is filled with default (0) value. + * Reads the data from the buffer. If the reading position is beyond the + * size of the real data, the real data are resized so this value can be + * read filling the new bytes with default (0) value. If the read overlaps + * the capacity of the buffer, only the bytes that still fall into the + * capacity are read and the rest is filled with default (0) value. * * @tparam The type of the data to read. This must be integral type. * * @param pos Position where to start the reading. - * @param endianness The endianness in which the data should be read. If not specified, default endianness assigned to DynamicBuffer is used. + * @param endianness The endianness in which the data should be read. + * If not specified, default endianness assigned to DynamicBuffer is used. * * @return The read value from the buffer. */ - template T read(uint32_t pos, retdec::utils::Endianness endianness = retdec::utils::Endianness::UNKNOWN) const + template T read( + uint32_t pos, + retdec::utils::Endianness endianness + = retdec::utils::Endianness::UNKNOWN) const { - static_assert(std::is_integral::value, "retdec::utils::DynamicBuffer::read can only accept integral types"); + static_assert( + std::is_integral::value, + "retdec::utils::DynamicBuffer::read can only accept integral types" + ); - // In case of non-specified endianness, use the default one assigned to DynamicBuffer itself + // In case of non-specified endianness, use the default one assigned + // to DynamicBuffer itself if (endianness == retdec::utils::Endianness::UNKNOWN) endianness = _endianness; @@ -80,21 +110,32 @@ class DynamicBuffer std::string readString(uint32_t pos, uint32_t maxLength = 0) const; /** - * Writes the data to the buffer. If the writing poisition is beyond the size of the real data, the real data are resized so this - * value can be written filling the new bytes with default (0) value. If the write overlaps the capacity of the buffer, only the bytes - * that still fall into the capacity are written and the rest is ignored. + * Writes the data to the buffer. If the writing poisition is beyond the + * size of the real data, the real data are resized so this value can be + * written filling the new bytes with default (0) value. If the write + * overlaps the capacity of the buffer, only the bytes that still fall + * into the capacity are written and the rest is ignored. * * @tparam The type of the data to write. This must be integral type. * * @param data The data to write. * @param pos The position where to start writing. - * @param endianness The endianness in which the data should be written. If not specified, default endianness assigned to DynamicBuffer is used. + * @param endianness The endianness in which the data should be written. + * If not specified, default endianness assigned to DynamicBuffer is used. */ - template void write(const T& data, uint32_t pos, retdec::utils::Endianness endianness = retdec::utils::Endianness::UNKNOWN) + template void write( + const T& data, + uint32_t pos, + retdec::utils::Endianness endianness + = retdec::utils::Endianness::UNKNOWN) { - static_assert(std::is_integral::value, "retdec::utils::DynamicBuffer::write can only accept integral types"); + static_assert( + std::is_integral::value, + "retdec::utils::DynamicBuffer::write can only accept integral types" + ); - // In case of non-specified endianness, use the default one assigned to DynamicBuffer itself + // In case of non-specified endianness, use the default one + // assigned to DynamicBuffer itself if (endianness == retdec::utils::Endianness::UNKNOWN) endianness = _endianness; @@ -104,7 +145,10 @@ class DynamicBuffer void writeRepeatingByte(uint8_t byte, uint32_t pos, uint32_t repeatAmount); private: - template void writeImpl(const T& data, uint32_t pos, retdec::utils::Endianness endianness) + template void writeImpl( + const T& data, + uint32_t pos, + retdec::utils::Endianness endianness) { // If the writing position is completely out of bounds, we just end if (pos >= _capacity) @@ -138,7 +182,9 @@ class DynamicBuffer } } - template T readImpl(uint32_t pos, retdec::utils::Endianness endianness) const + template T readImpl( + uint32_t pos, + retdec::utils::Endianness endianness) const { // We are at the end, we are unable to read anything if (pos >= _data.size()) @@ -148,7 +194,8 @@ class DynamicBuffer if (pos >= _capacity) return T{}; - // If reading overlaps over the size, make sure we don't access uninitialized memory + // If reading overlaps over the size, make sure we don't access + // uninitialized memory uint32_t bytesToRead = sizeof(T); if (pos + bytesToRead > getCapacity()) bytesToRead = getCapacity() - pos; diff --git a/include/retdec/utils/file_io.h b/include/retdec/utils/file_io.h index 10c57a6ac..ff9ca0d0c 100644 --- a/include/retdec/utils/file_io.h +++ b/include/retdec/utils/file_io.h @@ -20,7 +20,10 @@ namespace { */ const std::size_t FILE_BURST_READ_LENGTH = 0x100000; -template bool readBytes(std::istream& fileStream, std::vector& result, std::size_t desiredSize) +template bool readBytes( + std::istream& fileStream, + std::vector& result, + std::size_t desiredSize) { // We can read directly from the file without any conversions. if (sizeof(N) == 1) @@ -32,9 +35,11 @@ template bool readBytes(std::istream& fileStream, std::vector& r // Read and check for error bits // If badbit is set, then something bad happened and data are not valid. - // If EOF bit is not set and fail bit is set, then there was some other problem with reading data. - // If EOF bit and failbit are set, then it just means the file was truncated, but we should not report - // it as error. Instead, we just shrink the result buffer to the number of bytes we have read. + // If EOF bit is not set and fail bit is set, then there was some other + // problem with reading data. + // If EOF bit and failbit are set, then it just means the file was + // truncated, but we should not report it as error. Instead, we just + // shrink the result buffer to the number of bytes we have read. fileStream.read(buffer, desiredSize); if (fileStream.bad() || (!fileStream.eof() && fileStream.fail())) return false; @@ -61,12 +66,18 @@ template bool readBytes(std::istream& fileStream, std::vector& r return true; } -template bool writeBytes(std::ostream& fileStream, const std::vector& data, std::size_t desiredSize) +template bool writeBytes( + std::ostream& fileStream, + const std::vector& data, + std::size_t desiredSize) { // We can write directly to the file without any conversions. if (sizeof(N) == 1) { - fileStream.write(reinterpret_cast(data.data()), desiredSize); + fileStream.write( + reinterpret_cast(data.data()), + desiredSize + ); return fileStream.good(); } else @@ -88,14 +99,18 @@ template bool writeBytes(std::ostream& fileStream, const std::vecto * @param fileStream Representation of input file * @param result Into this parameter the resulting bytes are stored * @param start Start offset of read - * @param desiredSize Number of bytes for read. If this parameter is set to zero, - * function will read all bytes from @a start until end of file. + * @param desiredSize Number of bytes for read. If this parameter is set + * to zero, function will read all bytes from @a start until end of file. * * @return @c true if operation went OK, otherwise @c false * * If function returns @c false, @a bytes is set to empty vector */ -template bool readFile(std::istream& fileStream, std::vector& result, std::size_t start = 0, std::size_t desiredSize = 0) +template bool readFile( + std::istream& fileStream, + std::vector& result, + std::size_t start = 0, + std::size_t desiredSize = 0) { // Seek to the given offset and check if nothing bad happened fileStream.seekg(start, std::ios::beg); @@ -128,14 +143,18 @@ template bool readFile(std::istream& fileStream, std::vector& re * @param fileName Name of the file * @param result Into this parameter the resulting bytes are stored * @param start Start offset of read - * @param desiredSize Number of bytes for read. If this parameter is set to zero, - * function will read all bytes from @a start until end of file. + * @param desiredSize Number of bytes for read. If this parameter is set to + * zero, function will read all bytes from @a start until end of file. * * @return @c true if operation went OK, otherwise @c false * * If function returns @c false, @a bytes is set to empty vector */ -template bool readFile(const std::string& fileName, std::vector& result, std::size_t start = 0, std::size_t desiredSize = 0) +template bool readFile( + const std::string& fileName, + std::vector& result, + std::size_t start = 0, + std::size_t desiredSize = 0) { result.clear(); @@ -152,12 +171,16 @@ template bool readFile(const std::string& fileName, std::vector& * @param fileStream Representation of output file * @param data Data to write into the file * @param start Start offset of write - * @param desiredSize Number of bytes to write. If this parameter is set to zero, - * function will write all bytes from @c data. + * @param desiredSize Number of bytes to write. If this parameter is set + * to zero, function will write all bytes from @c data. * * @return @c true if operation went OK, otherwise @c false */ -template bool writeFile(std::ostream& fileStream, const std::vector& data, std::size_t start = 0, std::size_t desiredSize = 0) +template bool writeFile( + std::ostream& fileStream, + const std::vector& data, + std::size_t start = 0, + std::size_t desiredSize = 0) { fileStream.seekp(start, std::ios::beg); if (!fileStream.good()) @@ -176,14 +199,21 @@ template bool writeFile(std::ostream& fileStream, const std::vector * @param fileName Name of the file * @param data Data to write into the file * @param start Start offset of write - * @param desiredSize Number of bytes to write. If this parameter is set to zero, - * function will write all bytes from @c data. + * @param desiredSize Number of bytes to write. If this parameter is set + * to zero, function will write all bytes from @c data. * * @return @c true if operation went OK, otherwise @c false */ -template bool writeFile(const std::string& fileName, const std::vector& data, std::size_t start = 0, std::size_t desiredSize = 0) +template bool writeFile( + const std::string& fileName, + const std::vector& data, + std::size_t start = 0, + std::size_t desiredSize = 0) { - std::ofstream file(fileName, std::ios::out | std::ios::trunc | std::ios::binary); + std::ofstream file( + fileName, + std::ios::out | std::ios::trunc | std::ios::binary + ); if (!file.is_open()) return false; diff --git a/include/retdec/utils/string.h b/include/retdec/utils/string.h index 77625b502..746188922 100644 --- a/include/retdec/utils/string.h +++ b/include/retdec/utils/string.h @@ -161,10 +161,6 @@ void removeSuffix(std::string &n, const std::string &suffix = "_"); std::string removeSuffixRet(const std::string &n, const std::string &suffix = "_"); -// TODO: This is the same as toHex() in conversion.h -// Use implementation in conversion.h, but make it to take uint64_t or template. -std::string toHexString(unsigned long long val); - std::string normalizeName(const std::string &name); std::string normalizeNamePrefix(const std::string &name); diff --git a/include/retdec/utils/system.h b/include/retdec/utils/system.h index afdf219d6..3079d6f57 100644 --- a/include/retdec/utils/system.h +++ b/include/retdec/utils/system.h @@ -10,8 +10,6 @@ namespace retdec { namespace utils { -void sleep(unsigned seconds); - bool isLittleEndian(); bool systemHasLongDouble(); diff --git a/include/retdec/utils/test.h b/include/retdec/utils/test.h deleted file mode 100644 index a04ecf46c..000000000 --- a/include/retdec/utils/test.h +++ /dev/null @@ -1,21 +0,0 @@ -/** -* @file include/retdec/utils/test.h -* @brief Test-related macros. -* @copyright (c) 2017 Avast Software, licensed under the MIT license -* -* Created based on gtest's macro FRIEND_TEST. -* We can not use it directly because we would have to include gtest header in -* non-gtest-related sources, it would get propagated to modules which does -* not use gtest and we do not want them to use it. -*/ - -#ifndef RETDEC_UTILS_TEST_H -#define RETDEC_UTILS_TEST_H - -#define GTEST_FORWARD_TEST(testCaseName, testName)\ - namespace tests { class testCaseName##_##testName##_Test; } - -#define GTEST_FRIEND_TEST(testCaseName, testName)\ - friend class tests::testCaseName##_##testName##_Test - -#endif diff --git a/src/ar-extractor/archive_wrapper.cpp b/src/ar-extractor/archive_wrapper.cpp index 92aa3b388..a6a55e87a 100644 --- a/src/ar-extractor/archive_wrapper.cpp +++ b/src/ar-extractor/archive_wrapper.cpp @@ -85,7 +85,7 @@ bool checkError( std::string &errorMessage) { if (error) { - errorMessage = toString(std::move(error)); + errorMessage = llvm::toString(std::move(error)); return true; } @@ -119,7 +119,7 @@ ArchiveWrapper::ArchiveWrapper( Error error = Error::success(); archive = std::make_unique(buffer.get()->getMemBufferRef(), error); if (error) { - errorMessage = toString(std::move(error)); + errorMessage = llvm::toString(std::move(error)); return; } diff --git a/src/capstone2llvmirtool/capstone2llvmir.cpp b/src/capstone2llvmirtool/capstone2llvmir.cpp index 8fbbb17bd..e59020bab 100644 --- a/src/capstone2llvmirtool/capstone2llvmir.cpp +++ b/src/capstone2llvmirtool/capstone2llvmir.cpp @@ -18,10 +18,8 @@ #include "retdec/capstone2llvmir/capstone2llvmir.h" -using namespace std; - // byte ptr [0x12345678], 0x11 -vector CODE = retdec::utils::hexStringToBytes("80 05 78 56 34 12 11 00"); +std::vector CODE = retdec::utils::hexStringToBytes("80 05 78 56 34 12 11 00"); class ProgramOptions { @@ -145,28 +143,32 @@ class ProgramOptions case CS_ARCH_MAX: case CS_ARCH_ALL: default: - cerr << "Can not get Capstone arch to default Capstone basic mode." << endl; + std::cerr << "Can not get Capstone arch to default Capstone basic mode." << std::endl; exit(1); } } void dump() { - cout << endl; - cout << "Program Options:" << endl; - cout << "\t" << "arch : " << arch << " (" << _arch << ")" << endl; - cout << "\t" << "base : " << hex << base << " (" << _base << ")" << endl; - cout << "\t" << "code : " << retdec::utils::bytesToHexString(code) << " (" << _code << ")" << endl; - cout << "\t" << "asm text : " << text << endl; - cout << "\t" << "b mode : " << hex << basicMode << " (" << _basicMode << ")" << endl; - cout << "\t" << "e mode : " << hex << extraMode << " (" << _extraMode << ")" << endl; - cout << "\t" << "out : " << outFile << endl; - cout << endl; + std::string tmp; + retdec::utils::bytesToHexString(code, tmp, 0, 0, false, true); + std::cout << std::endl; + std::cout << "Program Options:" << std::endl; + std::cout << "\t" << "arch : " << arch << " (" << _arch << ")" << std::endl; + std::cout << "\t" << "base : " << std::hex << base << " (" << _base << ")" << std::endl; + std::cout << "\t" << "code : " << tmp << " (" << _code << ")" << std::endl; + std::cout << "\t" << "asm text : " << text << std::endl; + std::cout << "\t" << "b mode : " << std::hex << basicMode << " (" << _basicMode << ")" << std::endl; + std::cout << "\t" << "e mode : " << std::hex << extraMode << " (" << _extraMode << ")" << std::endl; + std::cout << "\t" << "out : " << outFile << std::endl; + std::cout << std::endl; } void printHelpAndDie() { - cout << _programName << ":\n" + std::string tmp; + retdec::utils::bytesToHexString(CODE, tmp, 0, 0, false, true); + std::cout << _programName << ":\n" "\t-a name Set architecture name.\n" "\t Possible values: arm, arm64, mips, x86, ppc, sparc, sysz, xcore\n" "\t Default value: x86.\n" @@ -174,7 +176,7 @@ class ProgramOptions "\t Default value 0x1000.\n" "\t-c code Binary data to translate in hexadecimal format.\n" "\t E.g. \"0b 84 d1 a0 80 60 40\" or \"0b84d1a0806040\".\n" - "\t Default value: \"" << retdec::utils::bytesToHexString(CODE) << "\"\n" + "\t Default value: \"" << tmp << "\"\n" "\t-t asm Assembly text to assemble, disassemble and dump.\n" "\t Most of the time, this is more convenient than -c option.\n" "\t-m mode Capstone basic mode to use.\n" @@ -193,19 +195,19 @@ class ProgramOptions public: cs_arch arch = CS_ARCH_X86; uint64_t base = 0x1000; - vector code = CODE; - string text; + std::vector code = CODE; + std::string text; cs_mode basicMode = CS_MODE_32; cs_mode extraMode = CS_MODE_LITTLE_ENDIAN; - string outFile = "-"; // "-" == stdout for llvm::raw_fd_ostream. + std::string outFile = "-"; // "-" == stdout for llvm::raw_fd_ostream. private: - string _programName = "capstone2llvmir"; - string _arch; - string _base; - string _code; - string _basicMode; - string _extraMode; + std::string _programName = "capstone2llvmir"; + std::string _arch; + std::string _base; + std::string _code; + std::string _basicMode; + std::string _extraMode; bool _useDefaultBasicMode = true; }; @@ -218,9 +220,9 @@ void printVersion() int minor = 0; int version = cs_version(&major, &minor); - cout << endl; - cout << "Capstone version: " << version << " (major: " << major - << ", minor: " << minor << ")" << endl; + std::cout << std::endl; + std::cout << "Capstone version: " << version << " (major: " << major + << ", minor: " << minor << ")" << std::endl; } ks_arch capstoneArchToKeystoneArch(cs_arch a) @@ -238,7 +240,7 @@ ks_arch capstoneArchToKeystoneArch(cs_arch a) case CS_ARCH_MAX: case CS_ARCH_ALL: default: - cerr << "Can not convert Capstone arch to Keystone arch." << endl; + std::cerr << "Can not convert Capstone arch to Keystone arch." << std::endl; exit(1); } } @@ -281,7 +283,7 @@ ks_mode capstoneModeBasicToKeystoneMode(cs_arch a, cs_mode m) } else { - cerr << "Can not convert Capstone basic mode to Keystone mode." << endl; + std::cerr << "Can not convert Capstone basic mode to Keystone mode." << std::endl; exit(1); } } @@ -314,7 +316,7 @@ ks_mode capstoneModeExtraToKeystoneMode(cs_arch a, cs_mode m) } else { - cerr << "Can not convert Capstone extra mode to Keystone mode." << endl; + std::cerr << "Can not convert Capstone extra mode to Keystone mode." << std::endl; exit(1); } } @@ -333,7 +335,7 @@ void assemble(ProgramOptions& po) if (ks_open(arch, basic | extra, &ks) != KS_ERR_OK) { ks_err err = ks_errno(ks); - cerr << "Keystone Error: " << ks_strerror(err) << endl; + std::cerr << "Keystone Error: " << ks_strerror(err) << std::endl; exit(1); } @@ -344,7 +346,7 @@ void assemble(ProgramOptions& po) if (ks_asm(ks, po.text.data(), po.base, &enc, &sz, &cnt) != KS_ERR_OK) { ks_err err = ks_errno(ks); - cerr << "Keystone Error: " << ks_strerror(err) << endl; + std::cerr << "Keystone Error: " << ks_strerror(err) << std::endl; exit(1); } @@ -359,7 +361,7 @@ void assemble(ProgramOptions& po) if (ks_close(ks) != KS_ERR_OK) { ks_err err = ks_errno(ks); - cerr << "Keystone Error: " << ks_strerror(err) << endl; + std::cerr << "Keystone Error: " << ks_strerror(err) << std::endl; exit(1); } } diff --git a/src/common/address.cpp b/src/common/address.cpp index 7faf15728..6edfd591f 100644 --- a/src/common/address.cpp +++ b/src/common/address.cpp @@ -11,7 +11,7 @@ #include #include "retdec/common/address.h" -// #include "retdec/common/string.h" +#include "retdec/utils/conversion.h" namespace retdec { namespace common { @@ -127,10 +127,7 @@ uint64_t Address::getValue() const std::string Address::toHexString() const { assert(isDefined()); - - std::stringstream ss; - ss << std::hex << address; - return ss.str(); + return utils::intToHexString(address); } std::string Address::toHexPrefixString() const diff --git a/src/common/function.cpp b/src/common/function.cpp index af5d27f6e..e64f20be2 100644 --- a/src/common/function.cpp +++ b/src/common/function.cpp @@ -7,9 +7,6 @@ #include #include "retdec/common/function.h" -#include "retdec/utils/const.h" - -using retdec::utils::likeConstVersion; namespace retdec { namespace common { diff --git a/src/cpdetect/heuristics/heuristics.cpp b/src/cpdetect/heuristics/heuristics.cpp index 6284700c9..ee33ca283 100644 --- a/src/cpdetect/heuristics/heuristics.cpp +++ b/src/cpdetect/heuristics/heuristics.cpp @@ -765,7 +765,7 @@ void Heuristics::getDwarfInfo() { for (std::size_t i = 0; i < noOfLanguages; ++i) { - addLanguage(languages[i], numToStr(modulesCounter[i]) + addLanguage(languages[i], std::to_string(modulesCounter[i]) + " module" + (modulesCounter[i] > 1 ? "s" : "")); } } diff --git a/src/cpdetect/heuristics/pe_heuristics.cpp b/src/cpdetect/heuristics/pe_heuristics.cpp index dca0761f5..b5439d525 100644 --- a/src/cpdetect/heuristics/pe_heuristics.cpp +++ b/src/cpdetect/heuristics/pe_heuristics.cpp @@ -197,7 +197,7 @@ std::string PeHeuristics::getEnigmaVersion() pos + pattern.length() + 1, result2)) { - return numToStr(result1) + "." + numToStr(result2); + return std::to_string(result1) + "." + std::to_string(result2); } } @@ -251,8 +251,8 @@ std::string PeHeuristics::getUpxAdditionalInfo(std::size_t metadataPos) auto id = static_cast(content[metadataPos + 28]); auto param = static_cast(content[metadataPos + 29]); - info += "[Filter: 0x" + numToStr(id, std::hex) - + ", Param: 0x" + numToStr(param, std::hex) + ']'; + info += "[Filter: 0x" + intToHexString(id) + + ", Param: 0x" + intToHexString(param) + ']'; } } @@ -333,7 +333,7 @@ void PeHeuristics::getVisualBasicHeuristics() unsigned long long version = 0; if (peParser.isVisualBasic(version)) { - addCompiler(source, strength, "Visual Basic", numToStr(version)); + addCompiler(source, strength, "Visual Basic", std::to_string(version)); addLanguage("Visual Basic"); } } @@ -1890,7 +1890,7 @@ void PeHeuristics::getNsPackSectionHeuristics() std::size_t counter = 0; for (std::size_t i = 1; i < noOfSections; ++i) { - if (sections[i]->getName() != (namePrefix + numToStr(i))) + if (sections[i]->getName() != (namePrefix + std::to_string(i))) { if (++counter > 1) { diff --git a/src/fileformat/file_format/elf/elf_format.cpp b/src/fileformat/file_format/elf/elf_format.cpp index 86eeef84f..1f28fbc21 100644 --- a/src/fileformat/file_format/elf/elf_format.cpp +++ b/src/fileformat/file_format/elf/elf_format.cpp @@ -2057,7 +2057,7 @@ void ElfFormat::loadInfoFromDynamicSegment() std::size_t segSz = getFileLength() - seg->get_offset(); seg->load(*reader.get_istream(), seg->get_offset(), segSz); - auto *dynamic = writer.sections.add("dynamic_" + numToStr(noOfDynTables++)); + auto *dynamic = writer.sections.add("dynamic_" + std::to_string(noOfDynTables++)); dynamic->set_type(SHT_DYNAMIC); dynamic->set_offset(seg->get_offset()); dynamic->set_address(seg->get_virtual_address()); diff --git a/src/fileformat/file_format/macho/macho_format.cpp b/src/fileformat/file_format/macho/macho_format.cpp index f8008f2da..1affb722b 100644 --- a/src/fileformat/file_format/macho/macho_format.cpp +++ b/src/fileformat/file_format/macho/macho_format.cpp @@ -952,7 +952,7 @@ void MachOFormat::dyldInfoCommand(const llvm::object::MachOObjectFile::LoadComma std::string name = exportRef.name().str(); if(name.empty()) { - exportSym.setName("exported_function_" + numToStr(exportRef.address(), std::hex)); + exportSym.setName("exported_function_" + intToHexString(exportRef.address())); } else { diff --git a/src/fileformat/file_format/pe/pe_format.cpp b/src/fileformat/file_format/pe/pe_format.cpp index b564eb35d..496dd1b3d 100644 --- a/src/fileformat/file_format/pe/pe_format.cpp +++ b/src/fileformat/file_format/pe/pe_format.cpp @@ -1511,7 +1511,7 @@ void PeFormat::loadExports() if(hasNonprintableChars(newExport.getName())) { - newExport.setName("exported_function_" + numToStr(newExport.getAddress(), std::hex)); + newExport.setName("exported_function_" + intToHexString(newExport.getAddress())); } exportTable->addExport(newExport); } @@ -1576,13 +1576,13 @@ void PeFormat::loadPdbInfo() get2ByteOffset(guidOffset + 6, res3) && get2ByteOffset(guidOffset + 8, res4, getInverseEndianness()) && getXByteOffset(guidOffset + 10, 6, res5, getInverseEndianness())) { - pdbInfo->setGuid(toUpper(numToStr(res1, std::hex) + "-" + numToStr(res2, std::hex) + "-" + - numToStr(res3, std::hex) + "-" + numToStr(res4, std::hex) + "-" + numToStr(res5, std::hex))); + pdbInfo->setGuid(toUpper(intToHexString(res1) + "-" + intToHexString(res2) + "-" + + intToHexString(res3) + "-" + intToHexString(res4) + "-" + intToHexString(res5))); } } else if(get4ByteOffset(guidOffset, res1)) { - pdbInfo->setGuid(toUpper(numToStr(res1, std::hex))); + pdbInfo->setGuid(toUpper(intToHexString(res1))); } const auto ageOffset = guidOffset + (isRsds ? 16 : 4); @@ -3658,39 +3658,51 @@ void PeFormat::scanForAnomalies() /** * Scan for section anomalies */ -void PeFormat::scanForSectionAnomalies() +void PeFormat::scanForSectionAnomalies(unsigned anamaliesLimit) { std::size_t nSecs = getDeclaredNumberOfSections(); unsigned long long epAddr; if (getEpAddress(epAddr)) { - const PeCoffSection *epSec = dynamic_cast(getEpSection()); + auto *epSec = dynamic_cast(getEpSection()); if (epSec) { // scan EP in last section const PeCoffSection *lastSec = (nSecs) ? getPeSection(nSecs - 1) : nullptr; if (epSec == lastSec) { - anomalies.emplace_back("EpInLastSection", "Entry point in the last section"); + anomalies.emplace_back( + "EpInLastSection", "Entry point in the last section" + ); } // scan EP in writable section if (epSec->getPeCoffFlags() & PELIB_IMAGE_SCN_MEM_WRITE) { - anomalies.emplace_back("EpInWritableSection", "Entry point in writable section"); + anomalies.emplace_back( + "EpInWritableSection", "Entry point in writable section" + ); } } else { // scan EP outside mapped sections - anomalies.emplace_back("EpOutsideSections", "Entry point is outside of mapped sections"); + anomalies.emplace_back( + "EpOutsideSections", "Entry point is outside of mapped sections" + ); } } - std::vector duplSections; + std::set duplSecNames; + std::set secNames; for (std::size_t i = 0; i < nSecs; i++) { + if (anomalies.size() > anamaliesLimit) + { + break; + } + auto sec = getPeSection(i); if (!sec) { @@ -3698,24 +3710,45 @@ void PeFormat::scanForSectionAnomalies() } const auto name = sec->getName(); - const std::string msgName = (name.empty()) ? numToStr(sec->getIndex()) : name; + auto pname = replaceNonprintableChars(name); + const std::string msgName = (name.empty()) ? std::to_string(sec->getIndex()) : name; + auto pmsgName = replaceNonprintableChars(msgName); const auto flags = sec->getPeCoffFlags(); if (!name.empty()) { + // scan for duplicit section names + bool duplName = duplSecNames.find(name) != duplSecNames.end(); + if (!duplName && secNames.find(name) != secNames.end()) + { + anomalies.emplace_back( + "DuplicitSectionNames", + "Multiple sections with name " + replaceNonprintableChars(name) + ); + duplSecNames.insert(name); + duplName = true; + } + secNames.insert(name); + // scan for packer section names if (usualPackerSections.find(name) != usualPackerSections.end()) { - if (std::find(duplSections.begin(), duplSections.end(), name) == duplSections.end()) + if (!duplName) { - anomalies.emplace_back("PackerSectionName", "Packer section name: " + replaceNonprintableChars(name)); + anomalies.emplace_back( + "PackerSectionName", + "Packer section name: " + pname + ); } } // scan for unusual section names else if (usualSectionNames.find(name) == usualSectionNames.end()) { - if (std::find(duplSections.begin(), duplSections.end(), name) == duplSections.end()) + if (!duplName) { - anomalies.emplace_back("UnusualSectionName", "Unusual section name: " + replaceNonprintableChars(name)); + anomalies.emplace_back( + "UnusualSectionName", + "Unusual section name: " + pname + ); } } @@ -3723,51 +3756,58 @@ void PeFormat::scanForSectionAnomalies() auto characIt = usualSectionCharacteristics.find(name); if (characIt != usualSectionCharacteristics.end() && characIt->second != flags) { - anomalies.emplace_back("UnusualSectionFlags", "Section " + replaceNonprintableChars(name) + " has unusual characteristics"); + anomalies.emplace_back( + "UnusualSectionFlags", + "Section " + pname + " has unusual characteristics" + ); } } // scan size over 100MB if (sec->getSizeInFile() >= 100000000UL) { - anomalies.emplace_back("LargeSection", "Section " + replaceNonprintableChars(msgName) + " has size over 100MB"); + anomalies.emplace_back( + "LargeSection", + "Section " + pmsgName + " has size over 100MB" + ); } // scan section marked uninitialized but contains data if ((flags & PELIB_IMAGE_SCN_CNT_UNINITIALIZED_DATA) && (sec->getOffset() != 0 || sec->getSizeInFile() != 0)) { - anomalies.emplace_back("UninitSectionHasData", "Section " + replaceNonprintableChars(msgName) + " is marked uninitialized but contains data"); + anomalies.emplace_back( + "UninitSectionHasData", + "Section " + pmsgName + " is marked uninitialized but contains data" + ); } for (std::size_t j = i + 1; j < nSecs; j++) { - auto cmpSec = getSection(j); - if (!cmpSec) + if (anomalies.size() > anamaliesLimit) { - continue; + break; } - // scan for duplicit section names - const auto cmpName = cmpSec->getName(); - if (!name.empty() && name == cmpName) + auto cmpSec = getSection(j); + if (!cmpSec) { - if (std::find(duplSections.begin(), duplSections.end(), name) == duplSections.end()) - { - anomalies.emplace_back("DuplicitSectionNames", "Multiple sections with name " + replaceNonprintableChars(name)); - duplSections.push_back(name); - } + continue; } // scan for overlapping sections auto secStart = sec->getOffset(); auto secEnd = secStart + sec->getSizeInFile(); + const auto cmpName = cmpSec->getName(); auto cmpSecStart = cmpSec->getOffset(); auto cmpSecEnd = cmpSecStart + cmpSec->getSizeInFile(); if ((secStart <= cmpSecStart && cmpSecStart < secEnd) || (cmpSecStart <= secStart && secStart < cmpSecEnd)) { - const std::string cmpMsgName = (cmpName.empty()) ? numToStr(cmpSec->getIndex()) : cmpName; - anomalies.emplace_back("OverlappingSections", "Sections " + replaceNonprintableChars(msgName) + " and " + replaceNonprintableChars(cmpMsgName) + " overlap"); + const std::string cmpMsgName = cmpName.empty() ? std::to_string(cmpSec->getIndex()) : cmpName; + anomalies.emplace_back( + "OverlappingSections", + "Sections " + pmsgName + " and " + replaceNonprintableChars(cmpMsgName) + " overlap" + ); } } } @@ -3792,7 +3832,7 @@ void PeFormat::scanForResourceAnomalies() } std::size_t nameId; - std::string msgName = (res->getNameId(nameId)) ? numToStr(nameId) : ""; + std::string msgName = (res->getNameId(nameId)) ? std::to_string(nameId) : ""; // scan for resource size over 100MB if (res->getSizeInFile() >= 100000000UL) @@ -3839,7 +3879,7 @@ void PeFormat::scanForImportAnomalies() } else { - msgName = numToStr(ordNum); + msgName = std::to_string(ordNum); } } @@ -3883,7 +3923,7 @@ void PeFormat::scanForExportAnomalies() } else { - msgName = numToStr(ordNum); + msgName = std::to_string(ordNum); } } diff --git a/src/fileformat/types/certificate_table/certificate.cpp b/src/fileformat/types/certificate_table/certificate.cpp index 72368257c..d0659a184 100644 --- a/src/fileformat/types/certificate_table/certificate.cpp +++ b/src/fileformat/types/certificate_table/certificate.cpp @@ -238,7 +238,7 @@ void Certificate::loadSignatureAlgorithm() void Certificate::loadSerialNumber() { if (auto sn = X509_get_serialNumber(certImpl)) - retdec::utils::bytesToHexString(sn->data, sn->length, serialNumber, 0, 0, /*uppercase=*/false); + retdec::utils::bytesToHexString(sn->data, sn->length, serialNumber, 0, 0, false); } void Certificate::loadIssuerAndSubject() @@ -273,8 +273,8 @@ void Certificate::calculateHashes() SHA1(reinterpret_cast(tmp.data()), tmp.size(), sha1Bytes.data()); SHA256(reinterpret_cast(tmp.data()), tmp.size(), sha256Bytes.data()); - retdec::utils::bytesToHexString(sha1Bytes, sha1Digest, 0, 0, /*uppercase=*/false); - retdec::utils::bytesToHexString(sha256Bytes, sha256Digest, 0, 0, /*uppercase=*/false); + retdec::utils::bytesToHexString(sha1Bytes, sha1Digest, 0, 0, false); + retdec::utils::bytesToHexString(sha256Bytes, sha256Digest, 0, 0, false); } /** diff --git a/src/fileformat/types/dotnet_types/dotnet_class.cpp b/src/fileformat/types/dotnet_types/dotnet_class.cpp index 58117f54a..b5ab50650 100644 --- a/src/fileformat/types/dotnet_types/dotnet_class.cpp +++ b/src/fileformat/types/dotnet_types/dotnet_class.cpp @@ -102,7 +102,7 @@ std::string DotnetClass::getNameWithParentClassIndex() const return name; } - return name + "." + numToStr(parent->getIndex() - 1); + return name + "." + std::to_string(parent->getIndex() - 1); } /** diff --git a/src/fileformat/types/dotnet_types/dotnet_data_types.cpp b/src/fileformat/types/dotnet_types/dotnet_data_types.cpp index 3d94c22a1..f4e24058f 100644 --- a/src/fileformat/types/dotnet_types/dotnet_data_types.cpp +++ b/src/fileformat/types/dotnet_types/dotnet_data_types.cpp @@ -47,8 +47,8 @@ std::string DotnetDataTypeArray::getText() const if (itr->first != 0 || itr->second != 0) { if (itr->first != 0) - dimStr += retdec::utils::numToStr(itr->first) + "..."; - dimStr += retdec::utils::numToStr(itr->second); + dimStr += std::to_string(itr->first) + "..."; + dimStr += std::to_string(itr->second); } repr += dimStr; diff --git a/src/fileformat/types/export_table/export_table.cpp b/src/fileformat/types/export_table/export_table.cpp index db2d88c21..f7b083e51 100644 --- a/src/fileformat/types/export_table/export_table.cpp +++ b/src/fileformat/types/export_table/export_table.cpp @@ -241,7 +241,10 @@ void ExportTable::dump(std::string &dumpTable) const for(const auto &exp : exports) { - ret << "; " << std::hex << exp.getName() << " (addr: " << exp.getAddress() << ", ord: " << std::dec << (exp.getOrdinalNumber(aux) ? numToStr(aux, std::dec) : "-") << ")\n"; + ret << "; " << std::hex << exp.getName() << " (addr: " + << exp.getAddress() << ", ord: " << std::dec + << (exp.getOrdinalNumber(aux) ? std::to_string(aux) : "-") + << ")\n"; } } diff --git a/src/fileformat/types/import_table/import_table.cpp b/src/fileformat/types/import_table/import_table.cpp index 819b698b5..d58969f8b 100644 --- a/src/fileformat/types/import_table/import_table.cpp +++ b/src/fileformat/types/import_table/import_table.cpp @@ -982,9 +982,9 @@ void ImportTable::dump(std::string &dumpTable) const for(const auto &imp : imports) { ret << "; " << std::hex << imp->getName() << " (addr: " << imp->getAddress() << - ", ord: " << std::dec << (imp->getOrdinalNumber(aux) ? numToStr(aux, std::dec) : "-") << + ", ord: " << std::dec << (imp->getOrdinalNumber(aux) ? std::to_string(aux) : "-") << ", libId: " << (imp->getLibraryIndex() < getNumberOfLibraries() ? - numToStr(imp->getLibraryIndex(), std::dec) : "-") << ")\n"; + std::to_string(imp->getLibraryIndex()) : "-") << ")\n"; } } @@ -1027,7 +1027,7 @@ void ImportTable::dumpLibrary(std::size_t libraryIndex, std::string &libraryDump for(const auto &i : indexes) { ret << "; " << std::hex << imports[i]->getName() << " (addr: " << imports[i]->getAddress() << - ", ord: " << std::dec << (imports[i]->getOrdinalNumber(aux) ? numToStr(aux, std::dec) : "-") << + ", ord: " << std::dec << (imports[i]->getOrdinalNumber(aux) ? std::to_string(aux) : "-") << ", libId: " << imports[i]->getLibraryIndex() << ")\n"; } } diff --git a/src/fileformat/types/relocation_table/relocation_table.cpp b/src/fileformat/types/relocation_table/relocation_table.cpp index 2e137940a..914459de9 100644 --- a/src/fileformat/types/relocation_table/relocation_table.cpp +++ b/src/fileformat/types/relocation_table/relocation_table.cpp @@ -168,7 +168,7 @@ void RelocationTable::dump(std::string &dumpTable) const for(const auto &item : table) { ret << "; " << std::hex << item.getName() << " (addr: " << item.getAddress() << - ", section: " << (item.getLinkToSection(aux) ? numToStr(aux) : "-") << + ", section: " << (item.getLinkToSection(aux) ? std::to_string(aux) : "-") << ", offset: " << item.getSectionOffset() << ") mask:"; for (const auto &byteMask : item.getMask()) diff --git a/src/fileformat/types/resource_table/resource_table.cpp b/src/fileformat/types/resource_table/resource_table.cpp index 018270a23..a9257998d 100644 --- a/src/fileformat/types/resource_table/resource_table.cpp +++ b/src/fileformat/types/resource_table/resource_table.cpp @@ -110,7 +110,7 @@ std::string ResourceTable::computePerceptualAvgHash(const ResourceIcon &icon) co } } - return retdec::utils::toHex(bytes, false, 16); + return retdec::utils::intToHexString(bytes, false, 16); } /** @@ -891,8 +891,8 @@ void ResourceTable::dump(std::string &dumpTable) const for(const auto &res : table) { - auto sName = (res->hasEmptyName() && res->getNameId(aux)) ? numToStr(aux, std::dec) : res->getName(); - auto sType = (res->hasEmptyType() && res->getTypeId(aux)) ? numToStr(aux, std::dec) : res->getType(); + auto sName = (res->hasEmptyName() && res->getNameId(aux)) ? std::to_string(aux) : res->getName(); + auto sType = (res->hasEmptyType() && res->getTypeId(aux)) ? std::to_string(aux) : res->getType(); auto sLang = res->getLanguage(); if(sType.empty()) { @@ -902,10 +902,10 @@ void ResourceTable::dump(std::string &dumpTable) const { if(res->getLanguageId(aux)) { - sLang = numToStr(aux, std::dec); + sLang = std::to_string(aux); if(res->getSublanguageId(aux)) { - sLang += ":" + numToStr(aux, std::dec); + sLang += ":" + std::to_string(aux); } } else @@ -915,8 +915,8 @@ void ResourceTable::dump(std::string &dumpTable) const } const auto md5 = res->hasMd5() ? res->getMd5() : "-"; ret << "; " << sName << " (type: " << sType << ", language: " << sLang << ", offset: " << - numToStr(res->getOffset(), std::hex) << ", declSize: " << numToStr(res->getSizeInFile(), std::hex) << - ", loadedSize: " << numToStr(res->getLoadedSize(), std::hex) << ", md5: " << md5 << ")\n"; + intToHexString(res->getOffset()) << ", declSize: " << intToHexString(res->getSizeInFile()) << + ", loadedSize: " << intToHexString(res->getLoadedSize()) << ", md5: " << md5 << ")\n"; } } diff --git a/src/fileformat/types/symbol_table/macho_symbol.cpp b/src/fileformat/types/symbol_table/macho_symbol.cpp index 7690d175d..c4609e05b 100644 --- a/src/fileformat/types/symbol_table/macho_symbol.cpp +++ b/src/fileformat/types/symbol_table/macho_symbol.cpp @@ -177,7 +177,7 @@ Export MachOSymbol::getAsExport() const Export exportSym; if(name.empty()) { - exportSym.setName("exported_function_" + numToStr(value, std::hex)); + exportSym.setName("exported_function_" + intToHexString(value)); } else { diff --git a/src/fileformat/types/symbol_table/symbol_table.cpp b/src/fileformat/types/symbol_table/symbol_table.cpp index 059023789..347ecff8d 100644 --- a/src/fileformat/types/symbol_table/symbol_table.cpp +++ b/src/fileformat/types/symbol_table/symbol_table.cpp @@ -309,10 +309,10 @@ void SymbolTable::dump(std::string &dumpTable) const usageType = "UNKN"; } - ret << "; " << item->getName() << " (addr: " << (item->getAddress(aux) ? numToStr(aux, std::hex) : "-") << + ret << "; " << item->getName() << " (addr: " << (item->getAddress(aux) ? intToHexString(aux) : "-") << ", index: " << item->getIndex() << ", type: " << type << ", usageType: " << usageType << - ", section: " << (item->getLinkToSection(aux) ? numToStr(aux) : "-") << - ", size: " << (item->getSize(aux) ? numToStr(aux) : "-") << ")\n"; + ", section: " << (item->getLinkToSection(aux) ? std::to_string(aux) : "-") << + ", size: " << (item->getSize(aux) ? std::to_string(aux) : "-") << ")\n"; } } diff --git a/src/fileformat/utils/asn1.cpp b/src/fileformat/utils/asn1.cpp index 5f48ebd47..5306f4a4b 100644 --- a/src/fileformat/utils/asn1.cpp +++ b/src/fileformat/utils/asn1.cpp @@ -201,8 +201,8 @@ void Asn1Object::init() // First number from OID is stored as 40*X + Y where OID is 'X.Y' auto first = contentData[0]; - _identifier += retdec::utils::numToStr(first / 40) + '.'; - _identifier += retdec::utils::numToStr(first % 40); + _identifier += std::to_string(first / 40) + '.'; + _identifier += std::to_string(first % 40); if (contentData.size() != 1) _identifier += '.'; @@ -216,7 +216,7 @@ void Asn1Object::init() continue; } - _identifier += retdec::utils::numToStr(subident); + _identifier += std::to_string(subident); if (itr + 1 != contentData.end()) _identifier += '.'; subident = 0; diff --git a/src/fileformat/utils/other.cpp b/src/fileformat/utils/other.cpp index 7a8bd7503..b4e5d8ad8 100644 --- a/src/fileformat/utils/other.cpp +++ b/src/fileformat/utils/other.cpp @@ -460,7 +460,7 @@ std::string lcidToStr(std::size_t lcid) auto l = lcids.find(lcid); if (l == lcids.end()) { - return numToStr(lcid, std::dec); + return std::to_string(lcid); } return l->second; } @@ -475,7 +475,7 @@ std::string codePageToStr(std::size_t cpage) auto cpg = codePages.find(cpage); if (cpg == codePages.end()) { - return numToStr(cpage, std::dec); + return std::to_string(cpage); } return cpg->second; } diff --git a/src/fileinfo/file_detector/coff_detector.cpp b/src/fileinfo/file_detector/coff_detector.cpp index fb626be6a..d406b2552 100644 --- a/src/fileinfo/file_detector/coff_detector.cpp +++ b/src/fileinfo/file_detector/coff_detector.cpp @@ -50,7 +50,7 @@ std::string getSymbolLinkToSection(std::int16_t link) return "DEBUG"; } - return numToStr(link - 1); + return std::to_string(link - 1); } /** diff --git a/src/fileinfo/file_detector/elf_detector.cpp b/src/fileinfo/file_detector/elf_detector.cpp index eaa8e015e..2a93a9de1 100644 --- a/src/fileinfo/file_detector/elf_detector.cpp +++ b/src/fileinfo/file_detector/elf_detector.cpp @@ -547,7 +547,7 @@ std::string getSymbolLinkToSection(unsigned long long link) case SHN_XINDEX: return "XINDEX"; default: - return numToStr(link); + return std::to_string(link); } } @@ -787,7 +787,7 @@ ElfDetector::ElfDetector( */ void ElfDetector::getFileVersion() { - fileInfo.setFileVersion(numToStr(elfParser->getFileVersion())); + fileInfo.setFileVersion(std::to_string(elfParser->getFileVersion())); } /** @@ -795,7 +795,7 @@ void ElfDetector::getFileVersion() */ void ElfDetector::getFileHeaderInfo() { - fileInfo.setFileHeaderVersion(numToStr(elfParser->getFileHeaderVersion())); + fileInfo.setFileHeaderVersion(std::to_string(elfParser->getFileHeaderVersion())); fileInfo.setFileHeaderSize(elfParser->getFileHeaderSize()); } @@ -1198,7 +1198,7 @@ void ElfDetector::getCoreInfo() auto name = mapGetValueOrDefault(auxVecMap, entry.first, ""); if(name.empty()) { - name = "UNKNOWN " + toString(entry.first); + name = "UNKNOWN " + std::to_string(entry.first); } fileInfo.addAuxVectorEntry(name, entry.second); } @@ -1284,7 +1284,7 @@ void ElfDetector::getOsAbiInfo() abi = "Architecture-specific ABI extension"; } fileInfo.setOsAbi(abi); - fileInfo.setOsAbiVersion(numToStr(abiVersion)); + fileInfo.setOsAbiVersion(std::to_string(abiVersion)); } /** @@ -1352,7 +1352,7 @@ void ElfDetector::getOsAbiInfoNote() if(elfParser->get4ByteOffset(notes[0].dataOffset, result)) { fileInfo.setOsAbi("Android"); - fileInfo.setOsAbiVersion(numToStr(result)); + fileInfo.setOsAbiVersion(std::to_string(result)); return; } } diff --git a/src/fileinfo/file_detector/macho_detector.cpp b/src/fileinfo/file_detector/macho_detector.cpp index 00426a314..10a172878 100644 --- a/src/fileinfo/file_detector/macho_detector.cpp +++ b/src/fileinfo/file_detector/macho_detector.cpp @@ -185,8 +185,8 @@ void MachODetector::getEncryption() { std::stringstream message; message << "Warning: This file is encrypted (encryption algorithm: " << id - << ", offset: " << numToStr(offset, hexWithPrefix) - << ", size: " << numToStr(size, hexWithPrefix) << ")."; + << ", offset: " << intToHexString(offset, true) + << ", size: " << intToHexString(size, true) << ")."; fileInfo.messages.push_back(message.str()); } } diff --git a/src/fileinfo/file_information/file_information_types/type_conversions.h b/src/fileinfo/file_information/file_information_types/type_conversions.h index 66e070fb4..8e644ec9f 100644 --- a/src/fileinfo/file_information/file_information_types/type_conversions.h +++ b/src/fileinfo/file_information/file_information_types/type_conversions.h @@ -26,15 +26,16 @@ std::string getBinaryRepresentation(unsigned long long number, unsigned long lon * For signed numeric types is incorrect value their minimal value (e.g. INT_MIN). * For unsigned numeric types is incorrect value their maximal value (e.g. UINT_MAX). */ -template std::string getNumberAsString(N number, std::ios_base &(* format)(std::ios_base &) = std::dec) +template std::string getNumberAsString( + N number, + std::ios_base &(* format)(std::ios_base &) = std::dec) { - if(!std::numeric_limits::is_signed && number != std::numeric_limits::max()) + if((!std::numeric_limits::is_signed && number != std::numeric_limits::max()) + || (std::numeric_limits::is_signed && number != std::numeric_limits::min())) { - return retdec::utils::numToStr(number, format); - } - else if(std::numeric_limits::is_signed && number != std::numeric_limits::min()) - { - return retdec::utils::numToStr(number, format); + std::ostringstream ss; + ss << format << number; + return ss.str(); } return ""; diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/anomalies_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/anomalies_plain_getter.cpp index c85ab5b0b..4e35bcbc7 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/anomalies_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/anomalies_plain_getter.cpp @@ -51,7 +51,7 @@ std::size_t AnomaliesPlainGetter::getBasicInfo(std::size_t structIndex, std::vec info.clear(); desc.push_back("Number of anomalies: "); - info.push_back(numToStr(fileinfo.getNumberOfAnomalies())); + info.push_back(std::to_string(fileinfo.getNumberOfAnomalies())); return info.size(); } @@ -64,7 +64,7 @@ bool AnomaliesPlainGetter::loadRecord(std::size_t structIndex, std::size_t recIn } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(fileinfo.getAnomalyIdentifier(recIndex)); record.push_back(fileinfo.getAnomalyDescription(recIndex)); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/data_directory_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/data_directory_plain_getter.cpp index ef67cd666..e748818cc 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/data_directory_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/data_directory_plain_getter.cpp @@ -50,7 +50,7 @@ std::size_t DataDirectoryPlainGetter::getBasicInfo(std::size_t structIndex, std: info.clear(); desc.push_back("Number of data directories: "); - info.push_back(numToStr(fileinfo.getNumberOfStoredDataDirectories())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredDataDirectories())); return info.size(); } @@ -63,7 +63,7 @@ bool DataDirectoryPlainGetter::loadRecord(std::size_t structIndex, std::size_t r } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(fileinfo.getDataDirectoryType(recIndex)); record.push_back(fileinfo.getDataDirectoryAddressStr(recIndex, hexWithPrefix)); record.push_back(fileinfo.getDataDirectorySizeStr(recIndex, hexWithPrefix)); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/dynamic_sections_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/dynamic_sections_plain_getter.cpp index 038a401bc..34be6c408 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/dynamic_sections_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/dynamic_sections_plain_getter.cpp @@ -74,7 +74,7 @@ bool DynamicSectionsPlainGetter::loadRecord(std::size_t structIndex, std::size_t std::vector desc, abbv; fileinfo.getDynamicEntryFlagsDescriptors(structIndex, recIndex, desc, abbv); record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(fileinfo.getDynamicEntryType(structIndex, recIndex)); record.push_back(abbvSerialization(abbv)); record.push_back(fileinfo.getDynamicEntryValueStr(structIndex, recIndex, hexWithPrefix)); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_auxv_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_auxv_plain_getter.cpp index c97cc9550..8454674ca 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_auxv_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_auxv_plain_getter.cpp @@ -67,7 +67,7 @@ std::size_t ElfAuxVPlainGetter::getBasicInfo( const auto& auxV = fileinfo.getElfCoreInfo().getAuxVector(); desc.push_back("Number of entries: "); - info.push_back(numToStr(auxV.size())); + info.push_back(std::to_string(auxV.size())); return info.size(); } @@ -86,9 +86,9 @@ bool ElfAuxVPlainGetter::loadRecord( auto& entry = fileinfo.getElfCoreInfo().getAuxVector()[recIndex]; record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(entry.first); - record.push_back(toHex(entry.second, true)); + record.push_back(intToHexString(entry.second, true)); return true; } diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_core_map_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_core_map_plain_getter.cpp index 02532f1fb..9da45d4a7 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_core_map_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_core_map_plain_getter.cpp @@ -73,7 +73,7 @@ std::size_t ElfCoreMapPlainGetter::getBasicInfo( const auto& fMap = fileinfo.getElfCoreInfo().getFileMap(); desc.push_back("Number of entries: "); - info.push_back(numToStr(fMap.size())); + info.push_back(std::to_string(fMap.size())); return info.size(); } @@ -92,8 +92,8 @@ bool ElfCoreMapPlainGetter::loadRecord( auto& entry = fileinfo.getElfCoreInfo().getFileMap()[recIndex]; record.clear(); - record.push_back(numToStr(recIndex)); - record.push_back(toHex(entry.address, true)); + record.push_back(std::to_string(recIndex)); + record.push_back(intToHexString(entry.address, true)); record.push_back(std::to_string(entry.size)); record.push_back(std::to_string(entry.page)); record.push_back(replaceNonprintableChars(entry.path)); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_notes_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_notes_plain_getter.cpp index 25f5c4edc..6f90a579a 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_notes_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/elf_notes_plain_getter.cpp @@ -89,9 +89,9 @@ std::size_t ElfNotesPlainGetter::getBasicInfo( desc.push_back("File offset : "); desc.push_back("Size in file : "); desc.push_back("Number of notes: "); - info.push_back(toHex(notes.getSecSegOffset(), true)); - info.push_back(numToStr(notes.getSecSegLength())); - info.push_back(numToStr(notes.getNotes().size())); + info.push_back(intToHexString(notes.getSecSegOffset(), true)); + info.push_back(std::to_string(notes.getSecSegLength())); + info.push_back(std::to_string(notes.getNotes().size())); return info.size(); } @@ -111,11 +111,11 @@ bool ElfNotesPlainGetter::loadRecord( const auto& note = notes.getNotes()[recIndex]; record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(replaceNonprintableChars(note.owner)); - record.push_back(toHex(note.type, true, 8)); - record.push_back(toHex(note.dataOffset, true, 8)); - record.push_back(numToStr(note.dataLength)); + record.push_back(intToHexString(note.type, true, 8)); + record.push_back(intToHexString(note.dataOffset, true, 8)); + record.push_back(std::to_string(note.dataLength)); record.push_back(replaceNonprintableChars(note.description)); return true; diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/export_table_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/export_table_plain_getter.cpp index fca6b958a..ebdd3d98d 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/export_table_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/export_table_plain_getter.cpp @@ -54,7 +54,7 @@ std::size_t ExportTablePlainGetter::getBasicInfo(std::size_t structIndex, std::v desc.push_back("CRC32 : "); desc.push_back("MD5 : "); desc.push_back("SHA256 : "); - info.push_back(numToStr(fileinfo.getNumberOfStoredExports())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredExports())); info.push_back(fileinfo.getExphashCrc32()); info.push_back(fileinfo.getExphashMd5()); info.push_back(fileinfo.getExphashSha256()); @@ -70,7 +70,7 @@ bool ExportTablePlainGetter::loadRecord(std::size_t structIndex, std::size_t rec } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(replaceNonprintableChars(fileinfo.getExportName(recIndex))); record.push_back(fileinfo.getExportOrdinalNumberStr(recIndex, std::dec)); record.push_back(fileinfo.getExportAddressStr(recIndex, hexWithPrefix)); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/import_table_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/import_table_plain_getter.cpp index 0187bb861..9899a8e33 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/import_table_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/import_table_plain_getter.cpp @@ -54,7 +54,7 @@ std::size_t ImportTablePlainGetter::getBasicInfo(std::size_t structIndex, std::v desc.push_back("CRC32 : "); desc.push_back("MD5 : "); desc.push_back("SHA256 : "); - info.push_back(numToStr(fileinfo.getNumberOfStoredImports())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredImports())); info.push_back(fileinfo.getImphashCrc32()); info.push_back(fileinfo.getImphashMd5()); info.push_back(fileinfo.getImphashSha256()); @@ -70,7 +70,7 @@ bool ImportTablePlainGetter::loadRecord(std::size_t structIndex, std::size_t rec } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(replaceNonprintableChars(fileinfo.getImportName(recIndex))); record.push_back(replaceNonprintableChars(fileinfo.getImportUsageType(recIndex))); record.push_back(fileinfo.getImportOrdinalNumberStr(recIndex, std::dec)); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/missing_deps_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/missing_deps_plain_getter.cpp index fafe7a4ad..28a98c6d7 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/missing_deps_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/missing_deps_plain_getter.cpp @@ -49,7 +49,7 @@ std::size_t MissingDepsPlainGetter::getBasicInfo(std::size_t structIndex, std::v } desc.push_back("Number of missing dependencies: "); - info.push_back(retdec::utils::numToStr(fileinfo.getNumberOfMissingDeps())); + info.push_back(std::to_string(fileinfo.getNumberOfMissingDeps())); return info.size(); } @@ -61,7 +61,7 @@ bool MissingDepsPlainGetter::loadRecord(std::size_t structIndex, std::size_t rec } record.clear(); - record.push_back(retdec::utils::numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(retdec::utils::replaceNonprintableChars(fileinfo.getMissingDepName(recIndex))); return true; } diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/pattern_matches_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/pattern_matches_plain_getter.cpp index 0e4b1a9d0..9956282ef 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/pattern_matches_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/pattern_matches_plain_getter.cpp @@ -60,10 +60,10 @@ bool PatternMatchesPlainGetter::loadRecord(std::size_t structIndex, std::size_t record.clear(); record.push_back(" "); unsigned long long val; - record.push_back(matches[recIndex].getOffset(val) ? numToStr(val, hexWithPrefix) : ""); - record.push_back(matches[recIndex].getAddress(val) ? numToStr(val, hexWithPrefix) : ""); - record.push_back(matches[recIndex].getDataSize(val) ? numToStr(val, hexWithPrefix) : ""); - record.push_back(matches[recIndex].getEntrySize(val) ? numToStr(val, std::dec) : ""); + record.push_back(matches[recIndex].getOffset(val) ? intToHexString(val) : ""); + record.push_back(matches[recIndex].getAddress(val) ? intToHexString(val) : ""); + record.push_back(matches[recIndex].getDataSize(val) ? intToHexString(val) : ""); + record.push_back(matches[recIndex].getEntrySize(val) ? std::to_string(val) : ""); record.push_back(matches[recIndex].isInteger() ? "yes" : "no"); record.push_back(matches[recIndex].isFloatingPoint() ? "yes" : "no"); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/relocation_tables_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/relocation_tables_plain_getter.cpp index bd8d72883..40b20cc36 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/relocation_tables_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/relocation_tables_plain_getter.cpp @@ -80,7 +80,7 @@ bool RelocationTablesPlainGetter::loadRecord(std::size_t structIndex, std::size_ } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(fileinfo.getRelocationTypeStr(structIndex, recIndex)); record.push_back(fileinfo.getRelocationOffsetStr(structIndex, recIndex, hexWithPrefix)); record.push_back(replaceNonprintableChars(fileinfo.getRelocationSymbolName(structIndex, recIndex))); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/resource_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/resource_plain_getter.cpp index 4db4975a6..ac13e9454 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/resource_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/resource_plain_getter.cpp @@ -58,7 +58,7 @@ std::size_t ResourcePlainGetter::getBasicInfo(std::size_t structIndex, std::vect desc.push_back("Icon MD5 : "); desc.push_back("Icon SHA256 : "); desc.push_back("Icon AvgHash : "); - info.push_back(numToStr(fileinfo.getNumberOfStoredResources())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredResources())); info.push_back(fileinfo.getResourceIconhashCrc32()); info.push_back(fileinfo.getResourceIconhashMd5()); info.push_back(fileinfo.getResourceIconhashSha256()); @@ -75,7 +75,7 @@ bool ResourcePlainGetter::loadRecord(std::size_t structIndex, std::size_t recInd } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); auto name = fileinfo.getResourceName(recIndex); shrinkAndReplaceNonprintable(name, MAX_NAME_LENGTH); const auto nameId = fileinfo.getResourceNameIdStr(recIndex, std::dec); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/rich_header_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/rich_header_plain_getter.cpp index 783a9b933..b988e5138 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/rich_header_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/rich_header_plain_getter.cpp @@ -49,7 +49,7 @@ std::size_t RichHeaderPlainGetter::getBasicInfo(std::size_t structIndex, std::ve info.clear(); desc.push_back("Number of records: "); - info.push_back(numToStr(fileinfo.getNumberOfStoredRecordsInRichHeader())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredRecordsInRichHeader())); return info.size(); } @@ -62,7 +62,7 @@ bool RichHeaderPlainGetter::loadRecord(std::size_t structIndex, std::size_t recI } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); const auto productId = fileinfo.getRichHeaderRecordProductIdStr(recIndex); const auto productBuild = fileinfo.getRichHeaderRecordProductBuildStr(recIndex); record.push_back(!productId.empty() && !productBuild.empty() ? productId + "." + productBuild : ""); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/section_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/section_plain_getter.cpp index 4af7b5ef5..0b6e48fec 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/section_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/section_plain_getter.cpp @@ -64,7 +64,7 @@ std::size_t SectionPlainGetter::getBasicInfo(std::size_t structIndex, std::vecto desc.push_back("CRC32 : "); desc.push_back("MD5 : "); desc.push_back("SHA256 : "); - info.push_back(numToStr(fileinfo.getNumberOfStoredSections())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredSections())); info.push_back(fileinfo.getSectionTableCrc32()); info.push_back(fileinfo.getSectionTableMd5()); info.push_back(fileinfo.getSectionTableSha256()); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/strings_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/strings_plain_getter.cpp index d6ec00ecc..6f035dc04 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/strings_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/strings_plain_getter.cpp @@ -51,7 +51,7 @@ std::size_t StringsPlainGetter::getBasicInfo(std::size_t structIndex, std::vecto info.clear(); desc.push_back("Number of strings: "); - info.push_back(numToStr(fileinfo.getNumberOfDetectedStrings())); + info.push_back(std::to_string(fileinfo.getNumberOfDetectedStrings())); return info.size(); } @@ -66,7 +66,7 @@ bool StringsPlainGetter::loadRecord(std::size_t structIndex, std::size_t recInde const auto& strings = fileinfo.getStrings(); record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(strings.getStringFileOffsetStr(recIndex, hexWithPrefix)); record.push_back(strings.getStringTypeStr(recIndex)); record.push_back(replaceNonprintableChars(strings.getStringSectionName(recIndex))); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/tls_info_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/tls_info_plain_getter.cpp index d88e550bc..bc00f35a8 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/tls_info_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/tls_info_plain_getter.cpp @@ -57,7 +57,7 @@ std::size_t TlsInfoPlainGetter::getBasicInfo(std::size_t structIndex, std::vecto desc.push_back("Address of index : "); desc.push_back("Size of zero fill : "); desc.push_back("Characteristics : "); - info.push_back(numToStr(fileinfo.getTlsNumberOfCallBacks())); + info.push_back(std::to_string(fileinfo.getTlsNumberOfCallBacks())); info.push_back(fileinfo.getTlsRawDataStartAddrStr(hexWithPrefix)); info.push_back(fileinfo.getTlsRawDataEndAddrStr(hexWithPrefix)); info.push_back(fileinfo.getTlsIndexAddrStr(hexWithPrefix)); @@ -76,7 +76,7 @@ bool TlsInfoPlainGetter::loadRecord(std::size_t structIndex, std::size_t recInde } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(fileinfo.getTlsCallBackAddrStr(recIndex, hexWithPrefix)); return true; } diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/typeref_table_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/typeref_table_plain_getter.cpp index 0fad47930..317da3980 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/typeref_table_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/typeref_table_plain_getter.cpp @@ -54,7 +54,7 @@ std::size_t TypeRefTablePlainGetter::getBasicInfo(std::size_t structIndex, std:: desc.push_back("CRC32 : "); desc.push_back("MD5 : "); desc.push_back("SHA256 : "); - info.push_back(numToStr(fileinfo.getNumberOfStoredDotnetImportedClasses())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredDotnetImportedClasses())); info.push_back(fileinfo.getDotnetTypeRefhashCrc32()); info.push_back(fileinfo.getDotnetTypeRefhashMd5()); info.push_back(fileinfo.getDotnetTypeRefhashSha256()); @@ -70,7 +70,7 @@ bool TypeRefTablePlainGetter::loadRecord(std::size_t structIndex, std::size_t re } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(replaceNonprintableChars(fileinfo.getDotnetImportedClassNameWithParentClassIndex(recIndex))); record.push_back(replaceNonprintableChars(fileinfo.getDotnetImportedClassNameSpace(recIndex))); record.push_back(replaceNonprintableChars(fileinfo.getDotnetImportedClassLibName(recIndex))); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/version_info_language_table_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/version_info_language_table_plain_getter.cpp index ddae248a7..2309d4328 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/version_info_language_table_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/version_info_language_table_plain_getter.cpp @@ -51,7 +51,7 @@ std::size_t VersionInfoLanguageTablePlainGetter::getBasicInfo(std::size_t struct info.clear(); desc.push_back("Number of languages: "); - info.push_back(numToStr(fileinfo.getNumberOfVersionInfoLanguages())); + info.push_back(std::to_string(fileinfo.getNumberOfVersionInfoLanguages())); return info.size(); } @@ -64,7 +64,7 @@ bool VersionInfoLanguageTablePlainGetter::loadRecord(std::size_t structIndex, st } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(fileinfo.getVersionInfoLanguageLcid(recIndex)); record.push_back(fileinfo.getVersionInfoLanguageCodePage(recIndex)); return true; diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/version_info_string_table_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/version_info_string_table_plain_getter.cpp index b61fe9cdb..ab1efae44 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/version_info_string_table_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/version_info_string_table_plain_getter.cpp @@ -51,7 +51,7 @@ std::size_t VersionInfoStringTablePlainGetter::getBasicInfo(std::size_t structIn info.clear(); desc.push_back("Number of strings: "); - info.push_back(numToStr(fileinfo.getNumberOfVersionInfoStrings())); + info.push_back(std::to_string(fileinfo.getNumberOfVersionInfoStrings())); return info.size(); } @@ -64,7 +64,7 @@ bool VersionInfoStringTablePlainGetter::loadRecord(std::size_t structIndex, std: } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(replaceNonprintableChars(fileinfo.getVersionInfoStringName(recIndex))); record.push_back(replaceNonprintableChars(fileinfo.getVersionInfoStringValue(recIndex))); return true; diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/visual_basic_extern_table_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/visual_basic_extern_table_plain_getter.cpp index 00cbebd01..b803200d3 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/visual_basic_extern_table_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_distribution_getter/visual_basic_extern_table_plain_getter.cpp @@ -55,7 +55,7 @@ std::size_t VisualBasicExternTablePlainGetter::getBasicInfo(std::size_t structIn desc.push_back("CRC32 : "); desc.push_back("MD5 : "); desc.push_back("SHA256 : "); - info.push_back(numToStr(fileinfo.getVisualBasicNumberOfExterns())); + info.push_back(std::to_string(fileinfo.getVisualBasicNumberOfExterns())); info.push_back(fileinfo.getVisualBasicExternTableHashCrc32()); info.push_back(fileinfo.getVisualBasicExternTableHashMd5()); info.push_back(fileinfo.getVisualBasicExternTableHashSha256()); @@ -71,7 +71,7 @@ bool VisualBasicExternTablePlainGetter::loadRecord(std::size_t structIndex, std: } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(replaceNonprintableChars(fileinfo.getVisualBasicExternApiName(recIndex))); record.push_back(replaceNonprintableChars(fileinfo.getVisualBasicExternModuleName(recIndex))); return true; diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_simple_getter/certificate_table_plain_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_simple_getter/certificate_table_plain_getter.cpp index 294579b4d..7301d2884 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_simple_getter/certificate_table_plain_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_simple_getter/certificate_table_plain_getter.cpp @@ -54,10 +54,10 @@ std::size_t CertificateTablePlainGetter::getBasicInfo(std::size_t structIndex, s desc.push_back("Number of certificates : "); desc.push_back("Signer certificate index : "); desc.push_back("Counter-signer certificate index: "); - info.push_back(numToStr(fileinfo.getNumberOfStoredCertificates())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredCertificates())); if(fileinfo.hasCertificateTableSignerCertificate()) { - info.push_back(numToStr(fileinfo.getCertificateTableSignerCertificateIndex())); + info.push_back(std::to_string(fileinfo.getCertificateTableSignerCertificateIndex())); } else { @@ -65,7 +65,7 @@ std::size_t CertificateTablePlainGetter::getBasicInfo(std::size_t structIndex, s } if(fileinfo.hasCertificateTableCounterSignerCertificate()) { - info.push_back(numToStr(fileinfo.getCertificateTableCounterSignerCertificateIndex())); + info.push_back(std::to_string(fileinfo.getCertificateTableCounterSignerCertificateIndex())); } else { diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/anomalies_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/anomalies_json_getter.cpp index f66d0ebeb..1ff49bc58 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/anomalies_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/anomalies_json_getter.cpp @@ -42,7 +42,7 @@ std::size_t AnomaliesJsonGetter::getBasicInfo(std::size_t structIndex, std::vect info.clear(); desc.push_back("numberOfAnomalies"); - info.push_back(numToStr(fileinfo.getNumberOfAnomalies())); + info.push_back(std::to_string(fileinfo.getNumberOfAnomalies())); return info.size(); } @@ -55,7 +55,7 @@ bool AnomaliesJsonGetter::getRecord(std::size_t structIndex, std::size_t recInde } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(fileinfo.getAnomalyIdentifier(recIndex)); record.push_back(fileinfo.getAnomalyDescription(recIndex)); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/data_directory_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/data_directory_json_getter.cpp index b67fdb230..a7f48314c 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/data_directory_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/data_directory_json_getter.cpp @@ -42,7 +42,7 @@ std::size_t DataDirectoryJsonGetter::getBasicInfo(std::size_t structIndex, std:: info.clear(); desc.push_back("numberOfDataDirectories"); - info.push_back(numToStr(fileinfo.getNumberOfStoredDataDirectories())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredDataDirectories())); return info.size(); } @@ -55,7 +55,7 @@ bool DataDirectoryJsonGetter::getRecord(std::size_t structIndex, std::size_t rec } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(fileinfo.getDataDirectoryType(recIndex)); record.push_back(fileinfo.getDataDirectoryAddressStr(recIndex, hexWithPrefix)); record.push_back(fileinfo.getDataDirectorySizeStr(recIndex, hexWithPrefix)); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/dynamic_sections_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/dynamic_sections_json_getter.cpp index 72d3d4085..99d8880c9 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/dynamic_sections_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/dynamic_sections_json_getter.cpp @@ -64,7 +64,7 @@ bool DynamicSectionsJsonGetter::getRecord(std::size_t structIndex, std::size_t r } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(toLower(fileinfo.getDynamicEntryType(structIndex, recIndex))); record.push_back(fileinfo.getDynamicEntryValueStr(structIndex, recIndex, hexWithPrefix)); record.push_back(fileinfo.getDynamicEntryDescription(structIndex, recIndex)); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/export_table_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/export_table_json_getter.cpp index 1fa38f852..e8eabb4a2 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/export_table_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/export_table_json_getter.cpp @@ -46,7 +46,7 @@ std::size_t ExportTableJsonGetter::getBasicInfo(std::size_t structIndex, std::ve desc.push_back("crc32"); desc.push_back("md5"); desc.push_back("sha256"); - info.push_back(numToStr(fileinfo.getNumberOfStoredExports())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredExports())); info.push_back(fileinfo.getExphashCrc32()); info.push_back(fileinfo.getExphashMd5()); info.push_back(fileinfo.getExphashSha256()); @@ -62,7 +62,7 @@ bool ExportTableJsonGetter::getRecord(std::size_t structIndex, std::size_t recIn } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(replaceNonprintableChars(fileinfo.getExportName(recIndex))); record.push_back(fileinfo.getExportOrdinalNumberStr(recIndex, std::dec)); record.push_back(fileinfo.getExportAddressStr(recIndex, hexWithPrefix)); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/import_table_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/import_table_json_getter.cpp index efd375157..1a70cc45a 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/import_table_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/import_table_json_getter.cpp @@ -50,7 +50,7 @@ std::size_t ImportTableJsonGetter::getBasicInfo(std::size_t structIndex, std::ve desc.push_back("crc32"); desc.push_back("md5"); desc.push_back("sha256"); - info.push_back(numToStr(fileinfo.getNumberOfStoredImports())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredImports())); info.push_back(fileinfo.getImphashCrc32()); info.push_back(fileinfo.getImphashMd5()); info.push_back(fileinfo.getImphashSha256()); @@ -66,7 +66,7 @@ bool ImportTableJsonGetter::getRecord(std::size_t structIndex, std::size_t recIn } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(replaceNonprintableChars(fileinfo.getImportName(recIndex))); record.push_back(replaceNonprintableChars(fileinfo.getImportUsageType(recIndex))); record.push_back(replaceNonprintableChars(fileinfo.getImportLibraryName(recIndex))); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/missing_deps_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/missing_deps_json_getter.cpp index 2bbbe8c88..88adf320e 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/missing_deps_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/missing_deps_json_getter.cpp @@ -51,7 +51,7 @@ bool MissingDepsJsonGetter::getRecord(std::size_t structIndex, std::size_t recIn } record.clear(); - record.push_back(retdec::utils::numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(retdec::utils::replaceNonprintableChars(fileinfo.getMissingDepName(recIndex))); return true; } diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/relocation_tables_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/relocation_tables_json_getter.cpp index 5f2016bb6..c220ff619 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/relocation_tables_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/relocation_tables_json_getter.cpp @@ -75,7 +75,7 @@ bool RelocationTablesJsonGetter::getRecord(std::size_t structIndex, std::size_t } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(fileinfo.getRelocationTypeStr(structIndex, recIndex)); record.push_back(fileinfo.getRelocationOffsetStr(structIndex, recIndex, hexWithPrefix)); record.push_back(replaceNonprintableChars(fileinfo.getRelocationSymbolName(structIndex, recIndex))); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/resource_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/resource_json_getter.cpp index 63e345d4a..8a6bd5f70 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/resource_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/resource_json_getter.cpp @@ -57,7 +57,7 @@ std::size_t ResourceJsonGetter::getBasicInfo(std::size_t structIndex, std::vecto desc.push_back("iconMd5"); desc.push_back("iconSha256"); desc.push_back("iconAvgHash"); - info.push_back(numToStr(fileinfo.getNumberOfStoredResources())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredResources())); info.push_back(fileinfo.getResourceIconhashCrc32()); info.push_back(fileinfo.getResourceIconhashMd5()); info.push_back(fileinfo.getResourceIconhashSha256()); @@ -74,7 +74,7 @@ bool ResourceJsonGetter::getRecord(std::size_t structIndex, std::size_t recIndex } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); auto name = fileinfo.getResourceName(recIndex); shrinkAndReplaceNonprintable(name, MAX_NAME_LENGTH); const auto nameId = fileinfo.getResourceNameIdStr(recIndex, std::dec); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/rich_header_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/rich_header_json_getter.cpp index 02f11ff89..9c31a59c9 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/rich_header_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/rich_header_json_getter.cpp @@ -51,7 +51,7 @@ std::size_t RichHeaderJsonGetter::getBasicInfo(std::size_t structIndex, std::vec info.push_back(fileinfo.getRichHeaderOffsetStr(hexWithPrefix)); info.push_back(fileinfo.getRichHeaderKeyStr(hexWithPrefix)); info.push_back(toLower(fileinfo.getRichHeaderSignature())); - info.push_back(numToStr(fileinfo.getNumberOfStoredRecordsInRichHeader())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredRecordsInRichHeader())); info.push_back(replaceNonprintableChars(fileinfo.getRichHeaderRawBytesStr())); return info.size(); @@ -65,7 +65,7 @@ bool RichHeaderJsonGetter::getRecord(std::size_t structIndex, std::size_t recInd } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); const auto productId = fileinfo.getRichHeaderRecordProductIdStr(recIndex); const auto productBuild = fileinfo.getRichHeaderRecordProductBuildStr(recIndex); record.push_back(!productId.empty() && !productBuild.empty() ? productId + "." + productBuild : ""); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/section_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/section_json_getter.cpp index 4a38883c6..111ec6624 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/section_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/section_json_getter.cpp @@ -63,7 +63,7 @@ std::size_t SectionJsonGetter::getBasicInfo(std::size_t structIndex, std::vector desc.push_back("crc32"); desc.push_back("md5"); desc.push_back("sha256"); - info.push_back(numToStr(fileinfo.getNumberOfStoredSections())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredSections())); info.push_back(fileinfo.getSectionTableCrc32()); info.push_back(fileinfo.getSectionTableMd5()); info.push_back(fileinfo.getSectionTableSha256()); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/strings_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/strings_json_getter.cpp index 8cb01a0f9..2a6dda14b 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/strings_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/strings_json_getter.cpp @@ -44,7 +44,7 @@ std::size_t StringsJsonGetter::getBasicInfo(std::size_t structIndex, std::vector info.clear(); desc.push_back("numberOfStrings"); - info.push_back(numToStr(fileinfo.getNumberOfDetectedStrings())); + info.push_back(std::to_string(fileinfo.getNumberOfDetectedStrings())); return info.size(); } @@ -59,7 +59,7 @@ bool StringsJsonGetter::getRecord(std::size_t structIndex, std::size_t recIndex, const auto& strings = fileinfo.getStrings(); record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(strings.getStringFileOffsetStr(recIndex, hexWithPrefix)); record.push_back(toLower(strings.getStringTypeStr(recIndex))); record.push_back(replaceNonprintableChars(strings.getStringSectionName(recIndex))); diff --git a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/typeref_table_json_getter.cpp b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/typeref_table_json_getter.cpp index 154da34c9..6da52207a 100644 --- a/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/typeref_table_json_getter.cpp +++ b/src/fileinfo/file_presentation/getters/iterative_getter/iterative_subtitle_getter/typeref_table_json_getter.cpp @@ -46,7 +46,7 @@ std::size_t TypeRefTableJsonGetter::getBasicInfo(std::size_t structIndex, std::v desc.push_back("crc32"); desc.push_back("md5"); desc.push_back("sha256"); - info.push_back(numToStr(fileinfo.getNumberOfStoredDotnetImportedClasses())); + info.push_back(std::to_string(fileinfo.getNumberOfStoredDotnetImportedClasses())); info.push_back(fileinfo.getDotnetTypeRefhashCrc32()); info.push_back(fileinfo.getDotnetTypeRefhashMd5()); info.push_back(fileinfo.getDotnetTypeRefhashSha256()); @@ -62,7 +62,7 @@ bool TypeRefTableJsonGetter::getRecord(std::size_t structIndex, std::size_t recI } record.clear(); - record.push_back(numToStr(recIndex)); + record.push_back(std::to_string(recIndex)); record.push_back(replaceNonprintableChars(fileinfo.getDotnetImportedClassNestedName(recIndex))); record.push_back(replaceNonprintableChars(fileinfo.getDotnetImportedClassNameSpace(recIndex))); record.push_back(replaceNonprintableChars(fileinfo.getDotnetImportedClassLibName(recIndex))); diff --git a/src/fileinfo/file_presentation/json_presentation.cpp b/src/fileinfo/file_presentation/json_presentation.cpp index 94022c91c..de25779eb 100644 --- a/src/fileinfo/file_presentation/json_presentation.cpp +++ b/src/fileinfo/file_presentation/json_presentation.cpp @@ -340,7 +340,7 @@ void JsonPresentation::presentMissingDepsInfo(Writer& writer) const writer.String("missingDeps"); writer.StartObject(); - serializeString(writer, "count", numToStr(numberOfMissingDeps)); + serializeString(writer, "count", std::to_string(numberOfMissingDeps)); presentIterativeSubtitle(writer, MissingDepsJsonGetter(fileinfo)); writer.EndObject(); } @@ -384,20 +384,20 @@ void JsonPresentation::presentCertificates(Writer& writer) const serializeString( writer, "numberOfCertificates", - numToStr(fileinfo.getNumberOfStoredCertificates())); + std::to_string(fileinfo.getNumberOfStoredCertificates())); if (fileinfo.hasCertificateTableSignerCertificate()) { serializeString( writer, "signerCertificateIndex", - numToStr(fileinfo.getCertificateTableSignerCertificateIndex())); + std::to_string(fileinfo.getCertificateTableSignerCertificateIndex())); } if (fileinfo.hasCertificateTableCounterSignerCertificate()) { serializeString( writer, "counterSignerCertificateIndex", - numToStr(fileinfo.getCertificateTableCounterSignerCertificateIndex())); + std::to_string(fileinfo.getCertificateTableCounterSignerCertificateIndex())); } writer.String("certificates"); @@ -409,7 +409,7 @@ void JsonPresentation::presentCertificates(Writer& writer) const serializeString( writer, "index", - numToStr(i)); + std::to_string(i)); serializeString( writer, "validSince", diff --git a/src/fileinfo/file_wrapper/pe/pe_wrapper.cpp b/src/fileinfo/file_wrapper/pe/pe_wrapper.cpp index ee6f13668..eafb61d7d 100644 --- a/src/fileinfo/file_wrapper/pe/pe_wrapper.cpp +++ b/src/fileinfo/file_wrapper/pe/pe_wrapper.cpp @@ -57,7 +57,7 @@ std::string getSymbolLinkToSection(word link) return "DEBUG"; } - return numToStr(link - 1); + return std::to_string(link - 1); } /** diff --git a/src/getsig/getsig.cpp b/src/getsig/getsig.cpp index 3ffae98be..78794857b 100644 --- a/src/getsig/getsig.cpp +++ b/src/getsig/getsig.cpp @@ -386,7 +386,7 @@ std::string getYaraRule( std::string condition = "$1 at "; if (options.isOffset) { - condition += numToStr(options.offset); + condition += std::to_string(options.offset); } else { diff --git a/src/idr2pat/idr2pat.cpp b/src/idr2pat/idr2pat.cpp index 2d2d3a345..50e86c2e3 100644 --- a/src/idr2pat/idr2pat.cpp +++ b/src/idr2pat/idr2pat.cpp @@ -104,7 +104,7 @@ std::string getRelocationsAsString( std::string result; for (const auto &reloc : relocations) { if (!reloc.second.empty()) { - result += toHex(reloc.first, false, 4) + " " + reloc.second + " "; + result += intToHexString(reloc.first, false, 4) + " " + reloc.second + " "; } } diff --git a/src/llvmir2hll/graphs/cfg/cfg.cpp b/src/llvmir2hll/graphs/cfg/cfg.cpp index 2f1323797..d8221287f 100644 --- a/src/llvmir2hll/graphs/cfg/cfg.cpp +++ b/src/llvmir2hll/graphs/cfg/cfg.cpp @@ -16,7 +16,6 @@ using retdec::utils::hasItem; using retdec::utils::removeItem; -using retdec::utils::toString; namespace retdec { namespace llvmir2hll { diff --git a/src/llvmir2hll/graphs/cfg/cfg_writer.cpp b/src/llvmir2hll/graphs/cfg/cfg_writer.cpp index 3e56d39cc..39bac95dd 100644 --- a/src/llvmir2hll/graphs/cfg/cfg_writer.cpp +++ b/src/llvmir2hll/graphs/cfg/cfg_writer.cpp @@ -8,8 +8,6 @@ #include "retdec/llvmir2hll/support/debug.h" #include "retdec/utils/conversion.h" -using retdec::utils::toString; - namespace retdec { namespace llvmir2hll { diff --git a/src/llvmir2hll/graphs/cfg/cfg_writers/graphviz_cfg_writer.cpp b/src/llvmir2hll/graphs/cfg/cfg_writers/graphviz_cfg_writer.cpp index 7193a8eb7..274f47bf5 100644 --- a/src/llvmir2hll/graphs/cfg/cfg_writers/graphviz_cfg_writer.cpp +++ b/src/llvmir2hll/graphs/cfg/cfg_writers/graphviz_cfg_writer.cpp @@ -21,7 +21,6 @@ using retdec::utils::hasItem; using retdec::utils::replaceCharsWithStrings; -using retdec::utils::toString; namespace retdec { namespace llvmir2hll { @@ -63,7 +62,9 @@ std::string createLabel(const std::string &str) { */ std::string cfgNodeToGraphvizNode(ShPtr cfgNode) { // To ensure uniqueness, we use the node's address. - return "Node" + createLabel(toString(cfgNode.get())); + return "Node" + createLabel( + std::to_string(reinterpret_cast(cfgNode.get())) + ); } /** diff --git a/src/llvmir2hll/graphs/cg/cg_writers/graphviz_cg_writer.cpp b/src/llvmir2hll/graphs/cg/cg_writers/graphviz_cg_writer.cpp index 43f9a7d8f..02d228c3b 100644 --- a/src/llvmir2hll/graphs/cg/cg_writers/graphviz_cg_writer.cpp +++ b/src/llvmir2hll/graphs/cg/cg_writers/graphviz_cg_writer.cpp @@ -13,8 +13,6 @@ #include "retdec/llvmir2hll/utils/graphviz.h" #include "retdec/utils/conversion.h" -using retdec::utils::toString; - namespace retdec { namespace llvmir2hll { diff --git a/src/llvmir2hll/hll/hll_writer.cpp b/src/llvmir2hll/hll/hll_writer.cpp index 50e189866..cb519e99d 100644 --- a/src/llvmir2hll/hll/hll_writer.cpp +++ b/src/llvmir2hll/hll/hll_writer.cpp @@ -50,8 +50,6 @@ using retdec::utils::hasItem; using retdec::utils::joinStrings; using retdec::utils::split; using retdec::utils::startsWith; -using retdec::utils::toHex; -using retdec::utils::toString; namespace retdec { namespace llvmir2hll { @@ -1260,7 +1258,7 @@ std::string HLLWriter::getRawGotoLabel(ShPtr stmt) { } // Fall-back. - return "generated_" + toString(currFuncGotoLabelCounter++); + return "generated_" + std::to_string(currFuncGotoLabelCounter++); } /** diff --git a/src/llvmir2hll/hll/hll_writers/c_hll_writer.cpp b/src/llvmir2hll/hll/hll_writers/c_hll_writer.cpp index 0128e1ac7..dcc801e08 100644 --- a/src/llvmir2hll/hll/hll_writers/c_hll_writer.cpp +++ b/src/llvmir2hll/hll/hll_writers/c_hll_writer.cpp @@ -107,7 +107,6 @@ using namespace retdec::llvm_support; using retdec::utils::addToSet; -using retdec::utils::toString; namespace retdec { namespace llvmir2hll { @@ -1963,7 +1962,7 @@ void CHLLWriter::emitStructDeclaration(ShPtr structType, ShPtr elemType(elements.at(i)); // Create a dummy variable so we can use emitVarWithType(). // All elements are named e#, where # is a number. - emitVarWithType(Variable::create("e" + toString(i), elemType)); + emitVarWithType(Variable::create("e" + std::to_string(i), elemType)); out->punctuation(';'); if (!emitInline) { out->newLine(); @@ -2095,7 +2094,7 @@ std::string CHLLWriter::genNameForUnnamedStruct(const StructTypeVector &usedStru std::string structName; // Create new names until we find a name without a clash. do { - structName = "struct" + toString(++unnamedStructCounter); + structName = "struct" + std::to_string(++unnamedStructCounter); for (const auto &type : usedStructTypes) { if (cast(type)->getName() == structName) { // We have found a clash, so try a different name. diff --git a/src/llvmir2hll/ir/statement.cpp b/src/llvmir2hll/ir/statement.cpp index 5f9e7383d..5b6d02a44 100644 --- a/src/llvmir2hll/ir/statement.cpp +++ b/src/llvmir2hll/ir/statement.cpp @@ -12,8 +12,6 @@ #include "retdec/llvmir2hll/support/debug.h" #include "retdec/utils/conversion.h" -using retdec::utils::toString; - namespace retdec { namespace llvmir2hll { namespace { diff --git a/src/llvmir2hll/optimizer/optimizer_manager.cpp b/src/llvmir2hll/optimizer/optimizer_manager.cpp index 8fd5365c3..a2306808e 100644 --- a/src/llvmir2hll/optimizer/optimizer_manager.cpp +++ b/src/llvmir2hll/optimizer/optimizer_manager.cpp @@ -4,6 +4,9 @@ * @copyright (c) 2017 Avast Software, licensed under the MIT license */ +#include +#include + #include "retdec/llvmir2hll/analysis/value_analysis.h" #include "retdec/llvmir2hll/graphs/cg/cg_builder.h" #include "retdec/llvmir2hll/hll/hll_writer.h" @@ -52,7 +55,6 @@ using namespace retdec::llvm_support; using namespace std::string_literals; using retdec::utils::hasItem; -using retdec::utils::sleep; using retdec::utils::startsWith; namespace retdec { @@ -322,7 +324,7 @@ void OptimizerManager::runOptimizerProvidedItShouldBeRun(ShPtr optimi optimizer->optimize(); } catch (const std::bad_alloc &) { printWarningMessage("out of memory; trying to recover"); - sleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); } } else { // Just run the optimizer and let std::bad_alloc propagate. diff --git a/src/llvmir2hll/utils/graphviz.cpp b/src/llvmir2hll/utils/graphviz.cpp index 88f2c8ce5..2aa5da74f 100644 --- a/src/llvmir2hll/utils/graphviz.cpp +++ b/src/llvmir2hll/utils/graphviz.cpp @@ -14,7 +14,6 @@ using namespace std::string_literals; using retdec::utils::addSlashes; -using retdec::utils::toHex; namespace retdec { namespace llvmir2hll { @@ -48,7 +47,7 @@ std::string UtilsGraphviz::createNodeName(const std::string &str) { // Every other character is converted into its hexadecimal // representation. else { - nodeName += toHex(c); + nodeName += utils::intToHexString(c); } } diff --git a/src/llvmir2hll/utils/string.cpp b/src/llvmir2hll/utils/string.cpp index df5cd2468..f2bffa6da 100644 --- a/src/llvmir2hll/utils/string.cpp +++ b/src/llvmir2hll/utils/string.cpp @@ -16,7 +16,6 @@ using retdec::utils::hasOnlyDecimalDigits; using retdec::utils::hasOnlyHexadecimalDigits; using retdec::utils::split; using retdec::utils::startsWith; -using retdec::utils::toHex; using retdec::utils::toLower; namespace retdec { @@ -43,7 +42,7 @@ std::string makeIdentifierValid(const std::string &id) { } else if (c == '.') { resId += '_'; } else { - resId += "_" + toHex(c) + "_"; + resId += "_" + utils::intToHexString(c) + "_"; } } return resId; diff --git a/src/llvmir2hll/var_renamer/var_renamer.cpp b/src/llvmir2hll/var_renamer/var_renamer.cpp index ae38a0897..26c68e733 100644 --- a/src/llvmir2hll/var_renamer/var_renamer.cpp +++ b/src/llvmir2hll/var_renamer/var_renamer.cpp @@ -21,7 +21,6 @@ using retdec::utils::hasItem; using retdec::utils::mapGetValueOrDefault; -using retdec::utils::toString; namespace retdec { namespace llvmir2hll { @@ -279,7 +278,7 @@ std::string VarRenamer::generateUniqueName(ShPtr var, // The name does not end with a number -> append numbers. unsigned varNum = 2; do { - newName = name + toString(varNum++); + newName = name + std::to_string(varNum++); } while (nameExists(newName, func)); } return newName; diff --git a/src/llvmir2hll/var_renamer/var_renamers/readable_var_renamer.cpp b/src/llvmir2hll/var_renamer/var_renamers/readable_var_renamer.cpp index 0d7592385..673d40956 100644 --- a/src/llvmir2hll/var_renamer/var_renamers/readable_var_renamer.cpp +++ b/src/llvmir2hll/var_renamer/var_renamers/readable_var_renamer.cpp @@ -31,7 +31,6 @@ using namespace std::string_literals; using retdec::utils::addToSet; using retdec::utils::arraySize; -using retdec::utils::toString; namespace retdec { namespace llvmir2hll { @@ -406,7 +405,7 @@ std::string ReadableVarRenamer::genNameForFuncParam( // number the parameters correctly, e.g. p2 is always the second parameter, // no matter if the first parameter has assigned a name from debug // information. - return "a"s + toString(func->getParamPos(var)); + return "a"s + std::to_string(func->getParamPos(var)); } void ReadableVarRenamer::visit(ShPtr stmt) { diff --git a/src/patterngen/pattern_extractor/types/symbol_pattern.cpp b/src/patterngen/pattern_extractor/types/symbol_pattern.cpp index 6cbdf0574..4f1e02bb7 100644 --- a/src/patterngen/pattern_extractor/types/symbol_pattern.cpp +++ b/src/patterngen/pattern_extractor/types/symbol_pattern.cpp @@ -34,7 +34,7 @@ std::string SymbolPattern::getReferenceString() const if (!ref.name.empty() && isPrintable(ref.name)) { // Only first reference is printed. if (!hasItem(used, ref.name)) { - result += toHex(ref.offset, false, 4) + " " + ref.name + " "; + result += intToHexString(ref.offset, false, 4) + " " + ref.name + " "; used.push_back(ref.name); } } diff --git a/src/utils/alignment.cpp b/src/utils/alignment.cpp index 08daaf623..ac1faff3a 100644 --- a/src/utils/alignment.cpp +++ b/src/utils/alignment.cpp @@ -10,17 +10,22 @@ namespace retdec { namespace utils { /** - * Checks whether given value is aligned based on alignment value. Alignment must be power of 2. + * Checks whether given value is aligned based on alignment value. + * Alignment must be power of 2. * * @param value Value to be checked. * @param alignment Alignment to check. Must be power of 2. - * @param remainder Output value that is non-zero if value is not aligned and zero if it is aligned. - * It contains @c value modulo @c alignment. Contains undefined value if alignment is not power of 2. + * @param remainder Output value that is non-zero if value is not aligned + * and zero if it is aligned. It contains @c value modulo @c alignment. + * Contains undefined value if alignment is not power of 2. * - * @return True if value is aligned to given alignment, false otherwise. If alignment is not power of 2 - * the return value is undefined. + * @return True if value is aligned to given alignment, false otherwise. + * If alignment is not power of 2 the return value is undefined. */ -bool isAligned(std::uint64_t value, std::uint64_t alignment, std::uint64_t& remainder) +bool isAligned( + std::uint64_t value, + std::uint64_t alignment, + std::uint64_t& remainder) { return (remainder = (value & (alignment - 1))) == 0; } @@ -31,7 +36,8 @@ bool isAligned(std::uint64_t value, std::uint64_t alignment, std::uint64_t& rema * @param value Value to align. * @param alignment Alignment to use. * - * @return Value aligned down. If alignment is not power of 2, return value is undefined. + * @return Value aligned down. If alignment is not power of 2, + * return value is undefined. */ std::uint64_t alignDown(std::uint64_t value, std::uint64_t alignment) { @@ -44,7 +50,8 @@ std::uint64_t alignDown(std::uint64_t value, std::uint64_t alignment) * @param value Value to align. * @param alignment Alignment to use. * - * @return Value aligned up. If alignment is not power of 2, return value is undefined. + * @return Value aligned up. If alignment is not power of 2, + * return value is undefined. */ std::uint64_t alignUp(std::uint64_t value, std::uint64_t alignment) { diff --git a/src/utils/byte_value_storage.cpp b/src/utils/byte_value_storage.cpp index e3b47abf5..c16e7425e 100644 --- a/src/utils/byte_value_storage.cpp +++ b/src/utils/byte_value_storage.cpp @@ -43,7 +43,10 @@ bool swapEndianness(std::string &str, std::size_t items, std::size_t length = 1) { for (std::size_t k = 0; k < length; ++k) { - std::swap(str[i + j * length + k], str[i + (items - j) * length - k - 1]); + std::swap( + str[i + j * length + k], + str[i + (items - j) * length - k - 1] + ); } } @@ -53,7 +56,10 @@ bool swapEndianness(std::string &str, std::size_t items, std::size_t length = 1) { for (std::size_t k = 0; k < middleLengthIndex; ++k) { - std::swap(str[i + j * length + k], str[i + (j + 1) * length - k - 1]); + std::swap( + str[i + j * length + k], + str[i + (j + 1) * length - k - 1] + ); } } } @@ -166,7 +172,13 @@ bool ByteValueStorage::hexToBig(std::string& str) const return false; } - return isBigEndian() ? true : swapEndianness(str, getBytesPerWord(), getNumberOfNibblesInByte()); + return isBigEndian() + ? true + : swapEndianness( + str, + getBytesPerWord(), + getNumberOfNibblesInByte() + ); } /** @@ -183,7 +195,13 @@ bool ByteValueStorage::hexToLittle(std::string& str) const return false; } - return isLittleEndian() ? true : swapEndianness(str, getBytesPerWord(), getNumberOfNibblesInByte()); + return isLittleEndian() + ? true + : swapEndianness( + str, + getBytesPerWord(), + getNumberOfNibblesInByte() + ); } /** @@ -255,7 +273,8 @@ bool ByteValueStorage::bitsToLittle(std::vector& values) const } /** - * Get integer (1B) located at provided address using the specified endian or default file endian + * Get integer (1B) located at provided address using the specified endian + * or default file endian * * @param address Address to get integer from * @param res Result integer @@ -263,13 +282,17 @@ bool ByteValueStorage::bitsToLittle(std::vector& values) const * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::get1Byte(std::uint64_t address, std::uint64_t& res, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::get1Byte( + std::uint64_t address, + std::uint64_t& res, + Endianness e) const { return getXByte(address, 1, res, e); } /** - * Get integer (2B) located at provided address using the specified endian or default file endian + * Get integer (2B) located at provided address using the specified endian + * or default file endian * * @param address Address to get integer from * @param res Result integer @@ -277,13 +300,17 @@ bool ByteValueStorage::get1Byte(std::uint64_t address, std::uint64_t& res, Endia * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::get2Byte(std::uint64_t address, std::uint64_t& res, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::get2Byte( + std::uint64_t address, + std::uint64_t& res, + Endianness e) const { return getXByte(address, 2, res, e); } /** - * Get integer (4B) located at provided address using the specified endian or default file endian + * Get integer (4B) located at provided address using the specified endian + * or default file endian * * @param address Address to get integer from * @param res Result integer @@ -291,13 +318,17 @@ bool ByteValueStorage::get2Byte(std::uint64_t address, std::uint64_t& res, Endia * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::get4Byte(std::uint64_t address, std::uint64_t& res, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::get4Byte( + std::uint64_t address, + std::uint64_t& res, + Endianness e) const { return getXByte(address, 4, res, e); } /** - * Get integer (8B) located at provided address using the specified endian or default file endian + * Get integer (8B) located at provided address using the specified endian + * or default file endian * * @param address Address to get integer from * @param res Result integer @@ -305,7 +336,10 @@ bool ByteValueStorage::get4Byte(std::uint64_t address, std::uint64_t& res, Endia * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::get8Byte(std::uint64_t address, std::uint64_t& res, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::get8Byte( + std::uint64_t address, + std::uint64_t& res, + Endianness e) const { return getXByte(address, 8, res, e); } @@ -337,7 +371,8 @@ bool ByteValueStorage::get10Byte(std::uint64_t address, long double& res) const } /** - * Get word located at provided address using the specified endian or default file endian + * Get word located at provided address using the specified endian + * or default file endian * * @param address Address to get integer from * @param res Result integer @@ -345,7 +380,10 @@ bool ByteValueStorage::get10Byte(std::uint64_t address, long double& res) const * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::getWord(std::uint64_t address, std::uint64_t& res, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::getWord( + std::uint64_t address, + std::uint64_t& res, + Endianness e) const { return getXByte(address, getBytesPerWord(), res, e); } @@ -397,7 +435,8 @@ bool ByteValueStorage::getDouble(std::uint64_t address, double& res) const } // 2.33 (0x4002a3d7 0a3d70a4) in data section as: a4703d0a d7a30240. // New ARM compilers are also generating this kind of double constants. - // We are not sure, what part of binary determines which kind of double constants are used. + // We are not sure, what part of binary determines which kind of double + // constants are used. // Currently we use new kind for ARMs > version 5. // To find relevant info, google: "ARM double mixed endian". @@ -406,7 +445,8 @@ bool ByteValueStorage::getDouble(std::uint64_t address, double& res) const } /** - * Set integer (1B) located at provided address using the specified endian or default file endian + * Set integer (1B) located at provided address using the specified endian + * or default file endian * * @param address Address to set integer at * @param val Integer to set @@ -414,13 +454,17 @@ bool ByteValueStorage::getDouble(std::uint64_t address, double& res) const * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::set1Byte(std::uint64_t address, std::uint64_t val, Endianness e /*= Endianness::UNKNOWN*/) +bool ByteValueStorage::set1Byte( + std::uint64_t address, + std::uint64_t val, + Endianness e) { return setXByte(address, 1, val, e); } /** - * Set integer (2B) located at provided address using the specified endian or default file endian + * Set integer (2B) located at provided address using the specified endian + * or default file endian * * @param address Address to set integer at * @param val Integer to set @@ -428,13 +472,17 @@ bool ByteValueStorage::set1Byte(std::uint64_t address, std::uint64_t val, Endian * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::set2Byte(std::uint64_t address, std::uint64_t val, Endianness e /*= Endianness::UNKNOWN*/) +bool ByteValueStorage::set2Byte( + std::uint64_t address, + std::uint64_t val, + Endianness e) { return setXByte(address, 2, val, e); } /** - * Set integer (4B) located at provided address using the specified endian or default file endian + * Set integer (4B) located at provided address using the specified endian + * or default file endian * * @param address Address to set integer at * @param val Integer to set @@ -442,13 +490,17 @@ bool ByteValueStorage::set2Byte(std::uint64_t address, std::uint64_t val, Endian * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::set4Byte(std::uint64_t address, std::uint64_t val, Endianness e /*= Endianness::UNKNOWN*/) +bool ByteValueStorage::set4Byte( + std::uint64_t address, + std::uint64_t val, + Endianness e) { return setXByte(address, 4, val, e); } /** - * Set integer (8B) located at provided address using the specified endian or default file endian + * Set integer (8B) located at provided address using the specified endian + * or default file endian * * @param address Address to set integer at * @param val Integer to set @@ -456,7 +508,10 @@ bool ByteValueStorage::set4Byte(std::uint64_t address, std::uint64_t val, Endian * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::set8Byte(std::uint64_t address, std::uint64_t val, Endianness e /*= Endianness::UNKNOWN*/) +bool ByteValueStorage::set8Byte( + std::uint64_t address, + std::uint64_t val, + Endianness e) { return setXByte(address, 8, val, e); } @@ -484,7 +539,8 @@ bool ByteValueStorage::set10Byte(std::uint64_t address, long double val) } /** - * Set word located at provided address using the specified endian or default file endian + * Set word located at provided address using the specified endian or default + * file endian * * @param address Address to set integer at * @param val Integer to set @@ -492,7 +548,10 @@ bool ByteValueStorage::set10Byte(std::uint64_t address, long double val) * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::setWord(std::uint64_t address, std::uint64_t val, Endianness e /*= Endianness::UNKNOWN*/) +bool ByteValueStorage::setWord( + std::uint64_t address, + std::uint64_t val, + Endianness e) { return setXByte(address, getBytesPerWord(), val, e); } @@ -541,15 +600,22 @@ bool ByteValueStorage::setDouble(std::uint64_t address, double val) * * @param address Address to get string from * @param res Result string - * @param size Requested size of string (if @a size is zero, read until zero byte) + * @param size Requested size of string (if @a size is zero, + * read until zero byte) * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::getNTBS(std::uint64_t address, std::string& res, std::size_t size/* = 0*/) const +bool ByteValueStorage::getNTBS( + std::uint64_t address, + std::string& res, + std::size_t size) const { using namespace std::placeholders; - GetNByteFn get1ByteFn = std::bind(&ByteValueStorage::get1Byte, this, _1, _2, _3); + GetNByteFn get1ByteFn = std::bind( + &ByteValueStorage::get1Byte, + this, _1, _2, _3 + ); return getNTBSImpl(get1ByteFn, address, res, size); } @@ -567,11 +633,17 @@ bool ByteValueStorage::getNTBS(std::uint64_t address, std::string& res, std::siz * Use this only if your are certain there is wide string on the address. * See @c getNTWSNice() for a faster wide-string-probing method. */ -bool ByteValueStorage::getNTWS(std::uint64_t address, std::size_t width, std::vector& res) const +bool ByteValueStorage::getNTWS( + std::uint64_t address, + std::size_t width, + std::vector& res) const { using namespace std::placeholders; - GetXByteFn getXByteFn = std::bind(&ByteValueStorage::getXByte, this, _1, _2, _3, _4); + GetXByteFn getXByteFn = std::bind( + &ByteValueStorage::getXByte, + this, _1, _2, _3, _4 + ); return getNTWSImpl(getXByteFn, address, width, res); } @@ -589,16 +661,23 @@ bool ByteValueStorage::getNTWS(std::uint64_t address, std::size_t width, std::ve * non-ASCII character. Use this for fast wide string probing. * See @c getNTWS() for a slower wide-string-forcing method. */ -bool ByteValueStorage::getNTWSNice(std::uint64_t address, std::size_t width, std::vector& res) const +bool ByteValueStorage::getNTWSNice( + std::uint64_t address, + std::size_t width, + std::vector& res) const { using namespace std::placeholders; - GetXByteFn getXByteFn = std::bind(&ByteValueStorage::getXByte, this, _1, _2, _3, _4); + GetXByteFn getXByteFn = std::bind( + &ByteValueStorage::getXByte, + this, _1, _2, _3, _4 + ); return getNTWSNiceImpl(getXByteFn, address, width, res); } /** - * Get integer (@a x bytes) array located at provided address using the specified array size and endian (or default file endian) + * Get integer (@a x bytes) array located at provided address using the + * specified array size and endian (or default file endian) * * @param address Address to get integer array from * @param x Number of bytes for one array item @@ -608,7 +687,12 @@ bool ByteValueStorage::getNTWSNice(std::uint64_t address, std::size_t width, std * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::getXByteArray(std::uint64_t address, std::uint64_t x, std::vector& res, std::size_t size, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::getXByteArray( + std::uint64_t address, + std::uint64_t x, + std::vector& res, + std::size_t size, + Endianness e) const { std::uint64_t r = 0; @@ -629,7 +713,8 @@ bool ByteValueStorage::getXByteArray(std::uint64_t address, std::uint64_t x, std } /** - * Get integer (1B) array located at provided address using the specified array size and endian (or default file endian) + * Get integer (1B) array located at provided address using the specified + * array size and endian (or default file endian) * * @param address Address to get integer array from * @param res Result integer array @@ -638,13 +723,18 @@ bool ByteValueStorage::getXByteArray(std::uint64_t address, std::uint64_t x, std * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::get1ByteArray(std::uint64_t address, std::vector& res, std::size_t size, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::get1ByteArray( + std::uint64_t address, + std::vector& res, + std::size_t size, + Endianness e) const { return getXByteArray(address, 1, res, size, e); } /** - * Get integer (2B) array located at provided address using the specified array size and endian (or default file endian) + * Get integer (2B) array located at provided address using the specified + * array size and endian (or default file endian) * * @param address Address to get integer array from * @param res Result integer array @@ -653,13 +743,18 @@ bool ByteValueStorage::get1ByteArray(std::uint64_t address, std::vector& res, std::size_t size, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::get2ByteArray( + std::uint64_t address, + std::vector& res, + std::size_t size, + Endianness e) const { return getXByteArray(address, 2, res, size, e); } /** - * Get integer (4B) array located at provided address using the specified array size and endian (or default file endian) + * Get integer (4B) array located at provided address using the specified + * array size and endian (or default file endian) * * @param address Address to get integer array from * @param res Result integer array @@ -668,13 +763,18 @@ bool ByteValueStorage::get2ByteArray(std::uint64_t address, std::vector& res, std::size_t size, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::get4ByteArray( + std::uint64_t address, + std::vector& res, + std::size_t size, + Endianness e) const { return getXByteArray(address, 4, res, size, e); } /** - * Get integer (8B) array located at provided address using the specified array size and endian (or default file endian) + * Get integer (8B) array located at provided address using the specified + * array size and endian (or default file endian) * * @param address Address to get integer array from * @param res Result integer array @@ -683,13 +783,18 @@ bool ByteValueStorage::get4ByteArray(std::uint64_t address, std::vector& res, std::size_t size, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::get8ByteArray( + std::uint64_t address, + std::vector& res, + std::size_t size, + Endianness e) const { return getXByteArray(address, 8, res, size, e); } /** - * Get long double (10B) array located at provided address using the specified array size + * Get long double (10B) array located at provided address using the specified + * array size * * @param address Address to get long double from * @param res Result long double array @@ -697,7 +802,10 @@ bool ByteValueStorage::get8ByteArray(std::uint64_t address, std::vector& res, std::size_t size) const +bool ByteValueStorage::get10ByteArray( + std::uint64_t address, + std::vector& res, + std::size_t size) const { long double r = 0; @@ -718,7 +826,8 @@ bool ByteValueStorage::get10ByteArray(std::uint64_t address, std::vector& res, std::size_t size, Endianness e/* = Endianness::UNKNOWN*/) const +bool ByteValueStorage::getWordArray( + std::uint64_t address, + std::vector& res, + std::size_t size, + Endianness e) const { return getXByteArray(address, getBytesPerWord(), res, size, e); } @@ -741,7 +854,10 @@ bool ByteValueStorage::getWordArray(std::uint64_t address, std::vector& res, std::size_t size) const +bool ByteValueStorage::getFloatArray( + std::uint64_t address, + std::vector& res, + std::size_t size) const { float r = 0; @@ -770,7 +886,10 @@ bool ByteValueStorage::getFloatArray(std::uint64_t address, std::vector& * * @return Status of operation (@c true if all is OK, @c false otherwise) */ -bool ByteValueStorage::getDoubleArray(std::uint64_t address, std::vector& res, std::size_t size) const +bool ByteValueStorage::getDoubleArray( + std::uint64_t address, + std::vector& res, + std::size_t size) const { double r = 0; @@ -795,7 +914,8 @@ bool ByteValueStorage::getDoubleArray(std::uint64_t address, std::vector * * @param data Vector of bytes * @param value Resulted value - * @param endian Endian - if specified it is forced, otherwise file's endian is used + * @param endian Endian - if specified it is forced, otherwise file's endian + * is used * @param offset Offset of first byte from @a data which will be converted * (0 means first offset from @a data) * @param size Number of bytes for conversion (0 means all bytes from @a offset @@ -803,9 +923,16 @@ bool ByteValueStorage::getDoubleArray(std::uint64_t address, std::vector * * @return @c true if conversion went OK, @c false otherwise */ -bool ByteValueStorage::createValueFromBytes(const std::vector& data, std::uint64_t& value, Endianness endian, std::uint64_t offset/* = 0*/, std::uint64_t size/* = 0*/) const +bool ByteValueStorage::createValueFromBytes( + const std::vector& data, + std::uint64_t& value, + Endianness endian, + std::uint64_t offset, + std::uint64_t size) const { - const std::uint64_t realSize = (!size || offset + size > data.size()) ? data.size() - offset : size; + const std::uint64_t realSize = (!size || offset + size > data.size()) + ? data.size() - offset + : size; if (offset >= data.size() || (size && realSize != size)) { return false; @@ -828,7 +955,9 @@ bool ByteValueStorage::createValueFromBytes(const std::vector& dat for (std::uint64_t i = 0; i < realSize; ++i) { - value += static_cast(data[offset + i]) << (getByteLength() * (endian == Endianness::LITTLE ? i : realSize - i - 1)); + value += static_cast(data[offset + i]) + << (getByteLength() + * (endian == Endianness::LITTLE ? i : realSize - i - 1)); } return true; @@ -840,11 +969,16 @@ bool ByteValueStorage::createValueFromBytes(const std::vector& dat * @param data Integer * @param x Width of integer * @param value Resulted vector of bytes - * @param endian Endian - if specified it is forced, otherwise file's endian is used + * @param endian Endian - if specified it is forced, otherwise file's + * endian is used * * @return @c true if conversion went OK, @c false otherwise */ -bool ByteValueStorage::createBytesFromValue(std::uint64_t data, std::uint64_t x, std::vector& value, Endianness endian) const +bool ByteValueStorage::createBytesFromValue( + std::uint64_t data, + std::uint64_t x, + std::vector& value, + Endianness endian) const { if (endian == Endianness::UNKNOWN && isLittleEndian()) { @@ -873,7 +1007,9 @@ bool ByteValueStorage::createBytesFromValue(std::uint64_t data, std::uint64_t x, return true; } -bool ByteValueStorage::get10ByteImpl(const std::vector& data, long double& res) const +bool ByteValueStorage::get10ByteImpl( + const std::vector& data, + long double& res) const { if (systemHasLongDouble()) { @@ -889,7 +1025,9 @@ bool ByteValueStorage::get10ByteImpl(const std::vector& data, long return true; } -bool ByteValueStorage::getFloatImpl(const std::vector& data, float& res) const +bool ByteValueStorage::getFloatImpl( + const std::vector& data, + float& res) const { if (data.size() != sizeof(float)) { @@ -900,7 +1038,9 @@ bool ByteValueStorage::getFloatImpl(const std::vector& data, float return true; } -bool ByteValueStorage::getDoubleImpl(const std::vector& data, double& res) const +bool ByteValueStorage::getDoubleImpl( + const std::vector& data, + double& res) const { if (data.size() != sizeof(double)) { @@ -911,7 +1051,10 @@ bool ByteValueStorage::getDoubleImpl(const std::vector& data, doub return true; } -bool ByteValueStorage::getNTBSImpl(const GetNByteFn& get1ByteFn, std::uint64_t address, std::string& res, std::size_t size) const +bool ByteValueStorage::getNTBSImpl( + const GetNByteFn& get1ByteFn, + std::uint64_t address, + std::string& res, std::size_t size) const { std::uint64_t c = 0; auto suc = get1ByteFn(address, c, getEndianness()); @@ -930,7 +1073,11 @@ bool ByteValueStorage::getNTBSImpl(const GetNByteFn& get1ByteFn, std::uint64_t a return !res.empty(); } -bool ByteValueStorage::getNTWSImpl(const GetXByteFn& getXByteFn, std::uint64_t address, std::size_t width, std::vector& res) const +bool ByteValueStorage::getNTWSImpl( + const GetXByteFn& getXByteFn, + std::uint64_t address, + std::size_t width, + std::vector& res) const { std::vector tmp; std::uint64_t item = 0; @@ -959,7 +1106,11 @@ bool ByteValueStorage::getNTWSImpl(const GetXByteFn& getXByteFn, std::uint64_t a return ret; } -bool ByteValueStorage::getNTWSNiceImpl(const GetXByteFn& getXByteFn, std::uint64_t address, std::size_t width, std::vector& res) const +bool ByteValueStorage::getNTWSNiceImpl( + const GetXByteFn& getXByteFn, + std::uint64_t address, + std::size_t width, + std::vector& res) const { std::vector tmp; std::uint64_t item = 0; diff --git a/src/utils/conversion.cpp b/src/utils/conversion.cpp index 1526574b2..c2b729a44 100644 --- a/src/utils/conversion.cpp +++ b/src/utils/conversion.cpp @@ -14,103 +14,52 @@ namespace retdec { namespace utils { /** -* @brief Converts the given integer into its hexadecimal representation. -* -* @param[in] i Number to be converted. -* @param[in] addBase Prepends "0x" before the result. -* @param[in] fillToN If needed, prepends "0" before the result to get at least -* @c fillToN characters long string. -* -* If @a addBase is @c false, the base ("0x") is omitted. For example, -* toHex(247) returns @c "f7", while toHex(247, true) returns @c -* "0xf7". All letters in the result are lowercase. -*/ -std::string toHex(std::uint64_t i, bool addBase, unsigned fillToN) { - std::stringstream s; - if (fillToN) { - s << std::setfill('0') << std::setw(fillToN) << std::hex << i; - } - else { - s << std::hex << i; - } - return addBase ? "0x" + s.str() : s.str(); -} - -/** -* @brief Transforms an 8-bit byte (i.e. string consisting of 0s and 1s) to -* unsigned long. -* -* @param[in] sByte String to be converted. -* @param[in] switchBitsOrder Whether to switch LSB and MSB or not. -* -* @return The resulting converted number or 0 if an error occurred. -*/ -unsigned long byteToULong8(const char *sByte, bool switchBitsOrder) { - std::bitset<8> byte; - - if (switchBitsOrder) { - for (int k=7; k>=0; k--) { - if (sByte[k] == '1') - byte[k] = 1; - else if (sByte[k] == '0') - byte[k] = 0; - else - return 0; - } - } else { - // This is the default behavior - we work only with big endian. - for (int k=0; k<=7; k++) { - if (sByte[k] == '1') - byte[7-k] = 1; - else if (sByte[k] == '0') - byte[7-k] = 0; - else - return 0; - } - } - - return byte.to_ulong(); -} - -/** -* @brief Transforms a byte (i.e. string consisting of 0s and 1s) to -* unsigned long for variable size of byte. -* -* @param[in] sByte String to be converted. -* @param[in] iByteSize Number of bits. -* -* @return The resulting converted number or 0 if an error occurred. -*/ -unsigned long byteToULongVariable(const char *sByte, std::size_t iByteSize) { - unsigned long value = 0; - unsigned long add = 1; - - // We work only with big endian. - for (int k = iByteSize - 1; k >= 0; k--) { - if (sByte[k] == '1') - value += add; - else if (sByte[k] != '0') - return 0; - add *= 2; - } - return value; -} - -/** -* @brief Transforms a byte (i.e. string consisting of 0s and 1s) to -* unsigned long for variable size of byte. -* -* @param[in] sByte String to be converted. -* @param[in] iByteSize Number of bits. -* @param[in] switchBitsOrder Whether to switch LSB and MSB or not. -* -* @return The resulting converted number or 0 if an error occurred. -*/ -unsigned long byteToULong(const char *sByte, std::size_t iByteSize, bool switchBitsOrder) { - if (iByteSize == 8) - return byteToULong8(sByte, switchBitsOrder); - else - return byteToULongVariable(sByte, iByteSize); + * From https://johnnylee-sde.github.io/Fast-unsigned-integer-to-hex-string/ + */ +char* byteToHexString(uint8_t b, bool uppercase) +{ + static char result[3] = {'\0', '\0', '\0'}; + static const char digits[513] = + "000102030405060708090A0B0C0D0E0F" + "101112131415161718191A1B1C1D1E1F" + "202122232425262728292A2B2C2D2E2F" + "303132333435363738393A3B3C3D3E3F" + "404142434445464748494A4B4C4D4E4F" + "505152535455565758595A5B5C5D5E5F" + "606162636465666768696A6B6C6D6E6F" + "707172737475767778797A7B7C7D7E7F" + "808182838485868788898A8B8C8D8E8F" + "909192939495969798999A9B9C9D9E9F" + "A0A1A2A3A4A5A6A7A8A9AAABACADAEAF" + "B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF" + "C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF" + "D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF" + "E0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF" + "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"; + static const char digitsLowerAlpha[513] = + "000102030405060708090a0b0c0d0e0f" + "101112131415161718191a1b1c1d1e1f" + "202122232425262728292a2b2c2d2e2f" + "303132333435363738393a3b3c3d3e3f" + "404142434445464748494a4b4c4d4e4f" + "505152535455565758595a5b5c5d5e5f" + "606162636465666768696a6b6c6d6e6f" + "707172737475767778797a7b7c7d7e7f" + "808182838485868788898a8b8c8d8e8f" + "909192939495969798999a9b9c9d9e9f" + "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf" + "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" + "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" + "e0e1e2e3e4e5e6e7e8e9eaebecedeeef" + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"; + + const char* lut = uppercase ? digits : digitsLowerAlpha; + std::size_t pos = b * 2; + result[0] = lut[pos]; + result[1] = lut[pos+1]; + + return &(result[0]); } /** @@ -213,60 +162,6 @@ std::string byteSwap32(const std::string &val) { val.substr(8, 8) + val.substr(0, 8); } -/** - * @brief Convert unsigned integer to binary number in text format. - * @param nValue Converted value. - * @param nLength Bitlength of result. - * @return Text representation of unsigned number in binary radix. - **/ -std::string unsignedToBinString(unsigned long long int nValue, int nLength) { - auto r = std::bitset<64>(nValue).to_string(); - return r.substr(r.length() - nLength); -} - -/** - * @brief Convert binary number in text format to unsigned integer. - * @param sValue text reprezentation of binary number - * @return value in dec radix without sign - **/ -unsigned long long int binStringToUnsigned(const char *sValue) { - char* end = nullptr; - return strtoull(sValue, &end, 2); -} - -/** - * Convert binary number in text format to signed int - * @param sValue text reprezentation of binary number in second supplement - * @return value in dec radix with sign - **/ -long long int binStringToSigned(const char *sValue) { - if (sValue[0] != '1') { - return binStringToUnsigned(sValue); - } - - bool bMeetOne = false; - int ii = static_cast(strlen(sValue)) - 1; - unsigned long long int nExp = 1; - unsigned long long int nReturn = 0; - - while (ii >= 0) { - // if we meet number one, we start to inverse future number. - if (!bMeetOne) { - if (sValue[ii] == '1') { - bMeetOne = true; - } - nReturn += sValue[ii] == '1' ? nExp : 0; - } - else { - nReturn += sValue[ii] == '1' ? 0 : nExp; - } - nExp *= 2; - ii--; - } - - return nReturn * (-1); -} - /** * Convert hexadecimal string @c hexIn string into bytes. * There might be whitespaces in the string, e.g. "0b 84 d1 a0 80 60 40" is @@ -287,28 +182,5 @@ std::vector hexStringToBytes(const std::string& hexIn) return bytes; } -/** - * Reverse function to @c hexStringToBytes(). It is using @c bytesToHexString() - * to do the conversion, but inserts space afer every byte, e.g. - * "0b 84 d1 a0 80 60 40". - */ -std::string bytesToHexString(const std::vector& bytes) -{ - std::string str; - bytesToHexString(bytes, str, 0, 0, false); - - std::stringstream ss; - for (std::size_t i = 0; i < str.size(); ++i) - { - ss << str[i]; - if (i % 2 == 1 && i < (str.size()-1)) - { - ss << " "; - } - } - - return ss.str(); -} - } // namespace utils } // namespace retdec diff --git a/src/utils/dynamic_buffer.cpp b/src/utils/dynamic_buffer.cpp index 9305eebfa..a37e7c4c8 100644 --- a/src/utils/dynamic_buffer.cpp +++ b/src/utils/dynamic_buffer.cpp @@ -12,11 +12,15 @@ namespace retdec { namespace utils { /** - * Creates the empty DynamicBuffer object with no capacity and specified endianness. + * Creates the empty DynamicBuffer object with no capacity and + * specified endianness. * * @param endianness Endianness of the bytes in the buffer. */ -DynamicBuffer::DynamicBuffer(Endianness endianness /*= Endianness::LITTLE*/) : _data(), _endianness(endianness), _capacity(0) +DynamicBuffer::DynamicBuffer(Endianness endianness) + : _data() + , _endianness(endianness) + , _capacity(0) { } @@ -26,20 +30,25 @@ DynamicBuffer::DynamicBuffer(Endianness endianness /*= Endianness::LITTLE*/) : _ * @param capacity Capacity of the buffer. * @param endianness Endianness of the bytes in the buffer. */ -DynamicBuffer::DynamicBuffer(uint32_t capacity, Endianness endianness /*= Endianness::LITTLE*/) +DynamicBuffer::DynamicBuffer(uint32_t capacity, Endianness endianness) : _data(), _endianness(endianness), _capacity(capacity) { _data.reserve(capacity); } /** - * Creates the DynamicBuffer object and fills it with specified data with specified endianness. + * Creates the DynamicBuffer object and fills it with specified data with + * specified endianness. * * @param data The bytes to initialize the buffer with. * @param endianness Endiannes of the bytes in the buffer. */ -DynamicBuffer::DynamicBuffer(const std::vector& data, Endianness endianness /*= Endianness::LITTLE*/) - : _data(data), _endianness(endianness), _capacity(static_cast(data.size())) +DynamicBuffer::DynamicBuffer( + const std::vector& data, + Endianness endianness) + : _data(data) + , _endianness(endianness) + , _capacity(static_cast(data.size())) { } @@ -49,21 +58,31 @@ DynamicBuffer::DynamicBuffer(const std::vector& data, Endianness endian * @param dynamicBuffer Buffer to copy. */ DynamicBuffer::DynamicBuffer(const DynamicBuffer& dynamicBuffer) - : _data(dynamicBuffer._data), _endianness(dynamicBuffer._endianness), _capacity(dynamicBuffer._capacity) + : _data(dynamicBuffer._data) + , _endianness(dynamicBuffer._endianness) + , _capacity(dynamicBuffer._capacity) { } /** - * Creates the copy of the DynamicBuffer object, but only the specified subbuffer. + * Creates the copy of the DynamicBuffer object, but only the + * specified subbuffer. * * @param dynamicBuffer Buffer to copy. - * @param startPos Starting position in the specified buffer where to start the copying. + * @param startPos Starting position in the specified buffer where to + * start the copying. * @param amount Number of bytes from startPos to copy. */ -DynamicBuffer::DynamicBuffer(const DynamicBuffer& dynamicBuffer, uint32_t startPos, uint32_t amount) +DynamicBuffer::DynamicBuffer( + const DynamicBuffer& dynamicBuffer, + uint32_t startPos, + uint32_t amount) { std::vector tmpBuffer = dynamicBuffer.getBuffer(); - std::vector buffer(tmpBuffer.begin() + startPos, tmpBuffer.begin() + startPos + amount); + std::vector buffer( + tmpBuffer.begin() + startPos, + tmpBuffer.begin() + startPos + amount + ); _data = buffer; _endianness = dynamicBuffer._endianness; @@ -107,9 +126,9 @@ uint32_t DynamicBuffer::getCapacity() const } /** - * Sets the endianness of the bytes in the buffer. It doesn't result in any changes - * to the actual bytes in the buffer. It reflects only when reading from or writing to - * the buffer. + * Sets the endianness of the bytes in the buffer. It doesn't result in any + * changes to the actual bytes in the buffer. It reflects only when reading + * from or writing to the buffer. * * @param endianness The endianness to set. */ @@ -186,13 +205,16 @@ void DynamicBuffer::forEach(const std::function& func) } /** - * Runs the specified function for every single byte in the DynamicBuffer in the reverse order. + * Runs the specified function for every single byte in the DynamicBuffer + * in the reverse order. * * @param func Function to run for every byte. */ void DynamicBuffer::forEachReverse(const std::function& func) { - for (std::vector::reverse_iterator itr = _data.rbegin(); itr != _data.rend(); ++itr) + for (std::vector::reverse_iterator itr = _data.rbegin(); + itr != _data.rend(); + ++itr) { uint8_t& byte = *itr; func(byte); @@ -203,16 +225,19 @@ void DynamicBuffer::forEachReverse(const std::function& func) * Reads the null or length terminated string from the buffer. * * @param pos The poisition in the buffer where to start reading. - * @param maxLength The maximal length of the string that is read. If this is 0, the length limit is ignored and the string is read up to the next 0 byte. + * @param maxLength The maximal length of the string that is read. If this is 0, + * the length limit is ignored and the string is read up to the next + * 0 byte. * * @return String read from buffer. */ -std::string DynamicBuffer::readString(uint32_t pos, uint32_t maxLength /*= 0*/) const +std::string DynamicBuffer::readString(uint32_t pos, uint32_t maxLength) const { std::string str; char ch; - while (((ch = read(pos++)) != 0) && (!maxLength || str.length() < maxLength)) + while (((ch = read(pos++)) != 0) + && (!maxLength || str.length() < maxLength)) str += ch; return str; @@ -223,9 +248,13 @@ std::string DynamicBuffer::readString(uint32_t pos, uint32_t maxLength /*= 0*/) * * @param byte The byte to write into the buffer. * @param pos The position where to start writing the byte. - * @param repeatAmount The number of times the byte is written into the buffer starting from pos including. + * @param repeatAmount The number of times the byte is written into the + * buffer starting from pos including. */ -void DynamicBuffer::writeRepeatingByte(uint8_t byte, uint32_t pos, uint32_t repeatAmount) +void DynamicBuffer::writeRepeatingByte( + uint8_t byte, + uint32_t pos, + uint32_t repeatAmount) { if (pos + repeatAmount > _capacity) repeatAmount = _capacity - pos; diff --git a/src/utils/string.cpp b/src/utils/string.cpp index e9b362dd8..dc70d5ece 100644 --- a/src/utils/string.cpp +++ b/src/utils/string.cpp @@ -49,17 +49,17 @@ bool isNonasciiChar(unsigned char c) { * their hexadecimal values. */ std::string replaceChars(const std::string &str, bool (* predicate)(unsigned char)) { - std::stringstream result; - const std::size_t maxC = (1 << (sizeof(std::string::value_type) * CHAR_BIT)) - 1; - for (const auto &c : str) { + std::string prefix("\\x"); + std::string result; + result.reserve(str.size() * 4); + for (const auto c : str) { if (predicate(c)) { - const auto val = numToStr(c & maxC, std::hex); - result << "\\x" << std::setw(2) << std::setfill('0') << val; + result += prefix + byteToHexString(c, false); } else { - result << c; + result += c; } } - return result.str(); + return result; } // @@ -442,8 +442,8 @@ std::string unicodeToAscii(const std::uint8_t *bytes, std::size_t nBytes) else { const std::size_t maxC = (1 << (sizeof(std::string::value_type) * CHAR_BIT)) - 1; - const auto val1 = numToStr(bytes[i] & maxC, std::hex); - const auto val2 = numToStr(bytes[i + 1] & maxC, std::hex); + const auto val1 = intToHexString(bytes[i] & maxC); + const auto val2 = intToHexString(bytes[i + 1] & maxC); result << "\\x" << std::setw(2) << std::setfill('0') << val1; result << "\\x" << std::setw(2) << std::setfill('0') << val2; } @@ -488,8 +488,8 @@ std::string unicodeToAscii(const std::uint8_t *bytes, std::size_t nBytes, std::s else { const std::size_t maxC = (1 << (sizeof(std::string::value_type) * CHAR_BIT)) - 1; - const auto val1 = numToStr(bytes[i] & maxC, std::hex); - const auto val2 = numToStr(bytes[i + 1] & maxC, std::hex); + const auto val1 = intToHexString(bytes[i] & maxC); + const auto val2 = intToHexString(bytes[i + 1] & maxC); result << "\\x" << std::setw(2) << std::setfill('0') << val1; result << "\\x" << std::setw(2) << std::setfill('0') << val2; } @@ -1134,15 +1134,6 @@ std::string removeSuffixRet(const std::string &n, const std::string &suffix) { return ret; } -/** -* @brief Returns hex-string form of the given integer. -*/ -std::string toHexString(unsigned long long val) { - std::stringstream ss; - ss << std::hex << val; - return ss.str(); -} - /** * @brief Replaces all special symbols by their normalized equivalent. * diff --git a/src/utils/system.cpp b/src/utils/system.cpp index 573df8713..669d2d8f0 100644 --- a/src/utils/system.cpp +++ b/src/utils/system.cpp @@ -7,28 +7,9 @@ #include "retdec/utils/os.h" #include "retdec/utils/system.h" -// sleep() -#ifdef OS_WINDOWS - #include -#else - #include -#endif - namespace retdec { namespace utils { -/** -* @brief Sleeps for the given number of seconds. -*/ -void sleep(unsigned seconds) { - #ifdef OS_WINDOWS - // The Windows version expects the number in milliseconds. - ::Sleep(seconds * 1000); - #else - ::sleep(seconds); - #endif -} - /** * @brief Finds out if the runtime architecture is little endian. */ diff --git a/tests/utils/CMakeLists.txt b/tests/utils/CMakeLists.txt index a4c1c7ada..3b0301b6c 100644 --- a/tests/utils/CMakeLists.txt +++ b/tests/utils/CMakeLists.txt @@ -4,7 +4,6 @@ add_executable(tests-utils array_tests.cpp binary_path_tests.cpp byte_value_storage_tests.cpp - const_tests.cpp container_tests.cpp conversion_tests.cpp filter_iterator_tests.cpp diff --git a/tests/utils/const_tests.cpp b/tests/utils/const_tests.cpp deleted file mode 100644 index 5f9464045..000000000 --- a/tests/utils/const_tests.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/** -* @file tests/utils/const_tests.cpp -* @brief Tests for the @c const module. -* @copyright (c) 2017 Avast Software, licensed under the MIT license -*/ - -#include - -#include - -#include "retdec/utils/const.h" - -using namespace ::testing; - -namespace retdec { -namespace utils { -namespace tests { - -/** -* @brief Tests for the @c const module. -*/ -class ConstTests: public Test {}; - -// -// likeConstVersion() -// - -TEST_F(ConstTests, -LikeConstVersionWorksCorrectly) { - class Array { - public: - // A user-provided constructor is needed for the creation of 'const - // Array' below. - Array() {} - - // const version - const int *getElement(std::size_t i) const { - return &array[i]; - } - - // non-const version - int *getElement(std::size_t i) { - return likeConstVersion(this, &Array::getElement, i); - } - - private: - int array[100] = {1}; - }; - - Array array; - ASSERT_EQ(1, *array.getElement(0)); - - const Array constArray; - ASSERT_EQ(1, *constArray.getElement(0)); -} - -} // namespace tests -} // namespace utils -} // namespace retdec diff --git a/tests/utils/conversion_tests.cpp b/tests/utils/conversion_tests.cpp index ef2d9347d..f6a2b7a35 100644 --- a/tests/utils/conversion_tests.cpp +++ b/tests/utils/conversion_tests.cpp @@ -20,76 +20,39 @@ namespace tests { class ConversionTests: public Test {}; // -// toHex() +// intToHexString() // TEST_F(ConversionTests, ToHexCorrectConversionNoBase) { - EXPECT_EQ("0", toHex(0x0, false)); - EXPECT_EQ("1", toHex(0x1, false)); - EXPECT_EQ("f", toHex(0xf, false)); - EXPECT_EQ("400", toHex(0x400, false)); - EXPECT_EQ("ffff", toHex(0xffff, false)); + EXPECT_EQ("0", intToHexString(0x0, false)); + EXPECT_EQ("1", intToHexString(0x1, false)); + EXPECT_EQ("f", intToHexString(0xf, false)); + EXPECT_EQ("400", intToHexString(0x400, false)); + EXPECT_EQ("ffff", intToHexString(0xffff, false)); } TEST_F(ConversionTests, ToHexCorrectConversionWithBase) { - EXPECT_EQ("0x0", toHex(0x0, true)); - EXPECT_EQ("0x1", toHex(0x1, true)); - EXPECT_EQ("0xf", toHex(0xf, true)); - EXPECT_EQ("0x400", toHex(0x400, true)); - EXPECT_EQ("0xffff", toHex(0xffff, true)); + EXPECT_EQ("0x0", intToHexString(0x0, true)); + EXPECT_EQ("0x1", intToHexString(0x1, true)); + EXPECT_EQ("0xf", intToHexString(0xf, true)); + EXPECT_EQ("0x400", intToHexString(0x400, true)); + EXPECT_EQ("0xffff", intToHexString(0xffff, true)); } TEST_F(ConversionTests, ToHexCorrectConversionWithFill) { - EXPECT_EQ("0x0", toHex(0x0, true, 0)); - EXPECT_EQ("0", toHex(0x0, false, 0)); - EXPECT_EQ("0x0000", toHex(0x0, true, 4)); - EXPECT_EQ("0000", toHex(0x0, false, 4)); - EXPECT_EQ("0x1234", toHex(0x1234, true, 2)); - EXPECT_EQ("1234", toHex(0x1234, false, 2)); - EXPECT_EQ("0x1234", toHex(0x1234, true, 4)); - EXPECT_EQ("1234", toHex(0x1234, false, 4)); - EXPECT_EQ("0x00001234", toHex(0x1234, true, 8)); - EXPECT_EQ("00001234", toHex(0x1234, false, 8)); -} - -// -// toString() -// - -TEST_F(ConversionTests, -ToStringBool) { - EXPECT_EQ("true", toString(true)); - EXPECT_EQ("false", toString(false)); -} - -TEST_F(ConversionTests, -ToStringInt) { - EXPECT_EQ("-100", toString(-100)); - EXPECT_EQ("-1", toString(-1)); - EXPECT_EQ("0", toString(0)); - EXPECT_EQ("1", toString(1)); - EXPECT_EQ("100", toString(100)); -} - -TEST_F(ConversionTests, -ToStringString) { - EXPECT_EQ("", toString(std::string(""))); - EXPECT_EQ("test", toString(std::string("test"))); -} - -TEST_F(ConversionTests, -ToStringCharPointer) { - EXPECT_EQ("", toString("")); - EXPECT_EQ("test", toString("test")); -} - -TEST_F(ConversionTests, -ToStringChar) { - EXPECT_EQ("a", toString('a')); - EXPECT_EQ("\n", toString('\n')); + EXPECT_EQ("0x0", intToHexString(0x0, true, 0)); + EXPECT_EQ("0", intToHexString(0x0, false, 0)); + EXPECT_EQ("0x0000", intToHexString(0x0, true, 4)); + EXPECT_EQ("0000", intToHexString(0x0, false, 4)); + EXPECT_EQ("0x1234", intToHexString(0x1234, true, 2)); + EXPECT_EQ("1234", intToHexString(0x1234, false, 2)); + EXPECT_EQ("0x1234", intToHexString(0x1234, true, 4)); + EXPECT_EQ("1234", intToHexString(0x1234, false, 4)); + EXPECT_EQ("0x00001234", intToHexString(0x1234, true, 8)); + EXPECT_EQ("00001234", intToHexString(0x1234, false, 8)); } // @@ -230,51 +193,6 @@ BytesToBits) { EXPECT_EQ(bytesToBits(u16vec), "1010110111101111"); } -// -// byteToULong() -// - -TEST_F(ConversionTests, -byteToULongSuccess) { - EXPECT_EQ(0, byteToULong("00000000", 8, false)); - EXPECT_EQ(1, byteToULong("00000001", 8, false)); - EXPECT_EQ(128, byteToULong("10000000", 8, false)); - EXPECT_EQ(255, byteToULong("11111111", 8, false)); - - EXPECT_EQ(0, byteToULong("00000000", 8, true)); - EXPECT_EQ(128, byteToULong("00000001", 8, true)); - EXPECT_EQ(1, byteToULong("10000000", 8, true)); - EXPECT_EQ(255, byteToULong("11111111", 8, true)); - - EXPECT_EQ(0, byteToULong("0000000000000000", 16)); - EXPECT_EQ(1, byteToULong("0000000000000001", 16)); - EXPECT_EQ(128, byteToULong("0000000010000000", 16)); - EXPECT_EQ(255, byteToULong("0000000011111111", 16)); - EXPECT_EQ(256, byteToULong("0000000100000000", 16)); - EXPECT_EQ(32768, byteToULong("1000000000000000", 16)); - EXPECT_EQ(65280, byteToULong("1111111100000000", 16)); - - EXPECT_EQ(1, byteToULong("1", 1)); - EXPECT_EQ(2, byteToULong("10", 2)); - EXPECT_EQ(7, byteToULong("111", 3)); -} - -TEST_F(ConversionTests, -byteToULongFailure) { - EXPECT_EQ(0, byteToULong("", 0, false)); - EXPECT_EQ(0, byteToULong("", 0, true)); - EXPECT_EQ(0, byteToULong("11111111", 0, false)); - EXPECT_EQ(0, byteToULong("11111111", 0, true)); - - EXPECT_EQ(0, byteToULong("10200000", 8, false)); - EXPECT_EQ(0, byteToULong("10200000", 8, true)); - - EXPECT_EQ(0, byteToULong("1x", 2, false)); - EXPECT_EQ(0, byteToULong("1x", 2, true)); - EXPECT_EQ(0, byteToULong("-1", 2, false)); - EXPECT_EQ(0, byteToULong("-1", 2, true)); -} - // // double10toDouble8() // @@ -340,54 +258,6 @@ byteSwap32SSuccess) { EXPECT_EQ("00000000000000000000000011111111", byteSwap32("11111111000000000000000000000000")); } -// -// unsignedToBinString() -// - -TEST_F(ConversionTests, -unsignedToBinStringSuccess) { - EXPECT_EQ("00000000000000011110001001000000", unsignedToBinString(123456, 32)); - EXPECT_EQ("011110001001000000", unsignedToBinString(123456, 18)); - EXPECT_EQ("11110001001000000", unsignedToBinString(123456, 17)); - EXPECT_EQ("1110001001000000", unsignedToBinString(123456, 16)); - EXPECT_EQ("01000000", unsignedToBinString(123456, 8)); - EXPECT_EQ("0", unsignedToBinString(123456, 1)); - EXPECT_EQ("", unsignedToBinString(123456, 0)); -} - -// -// binStringToUnsigned() -// - -TEST_F(ConversionTests, -binStringToUnsignedSuccess) { - EXPECT_EQ(123456, binStringToUnsigned("00000000000000011110001001000000")); - EXPECT_EQ(123456, binStringToUnsigned("011110001001000000")); - EXPECT_EQ(123456, binStringToUnsigned("11110001001000000")); - EXPECT_EQ(57920, binStringToUnsigned("1110001001000000")); - EXPECT_EQ(64, binStringToUnsigned("01000000")); - EXPECT_EQ(0, binStringToUnsigned("0")); - EXPECT_EQ(1, binStringToUnsigned("1")); - EXPECT_EQ(0, binStringToUnsigned("")); -} - -// -// binStringToSigned() -// - -TEST_F(ConversionTests, -binStringToSignedSuccess) { - EXPECT_EQ(123456, binStringToSigned("00000000000000011110001001000000")); - EXPECT_EQ(123456, binStringToSigned("011110001001000000")); - - EXPECT_EQ(-16448, binStringToSigned("1011111111000000")); - EXPECT_EQ(-6, binStringToSigned("11010")); - EXPECT_EQ(-13, binStringToSigned("10011")); - EXPECT_EQ(-2, binStringToSigned("1111111111111110")); - EXPECT_EQ(-12582809, binStringToSigned("11010000000000000001100111")); - EXPECT_EQ(-12578294, binStringToSigned("11010000000001001000001010")); -} - // // hexStringToBytes() // @@ -406,7 +276,9 @@ hexStringToBytesSuccess) { TEST_F(ConversionTests, bytesToHexStringSuccess) { std::vector vres = {0x0b, 0x84, 0xd1, 0xa0, 0x80, 0x60, 0x40}; - EXPECT_EQ("0b 84 d1 a0 80 60 40", bytesToHexString(vres)); + std::string res; + bytesToHexString(vres, res, 0, 0, false, true); + EXPECT_EQ("0b 84 d1 a0 80 60 40", res); } } // namespace tests diff --git a/tests/utils/string_tests.cpp b/tests/utils/string_tests.cpp index f2d3f0eec..03464e569 100644 --- a/tests/utils/string_tests.cpp +++ b/tests/utils/string_tests.cpp @@ -1269,16 +1269,6 @@ removeSuffixRetDoesNothingWhenSuffixNotFound) { EXPECT_EQ("object_1234", removeSuffixRet("object_1234", "=")); } -// -// toHexString() -// - -TEST_F(StringTests, -toHexStringSuccess) { - EXPECT_EQ("0", toHexString(0x0)); - EXPECT_EQ("123456789abcdef", toHexString(0x123456789abcdef)); -} - // // normalizeName() //