// == AUTOMATICALLY GENERATED by armips_gen.py, do not edit directly == // armips assembler v0.11 (commit 9029577f6448c78dadcffbc876d2b8cbcfc6da9b) // https://github.com/kingcom/armips // To simplify compilation, all files have been concatenated into one. // MIPS only, other architectures not included. /* The MIT License (MIT) Copyright (c) 2009-2020 Kingcom Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define ARMIPS_USE_STD_FILESYSTEM #pragma region "File: Util/FileSystem.h" #ifdef ARMIPS_USE_STD_FILESYSTEM #include #include namespace fs { using namespace std::filesystem; using ifstream = std::ifstream; using ofstream = std::ofstream; using fstream = std::fstream; } #else #include namespace fs { using namespace ghc::filesystem; using ifstream = ghc::filesystem::ifstream; using ofstream = ghc::filesystem::ofstream; using fstream = ghc::filesystem::fstream; } #endif #pragma region "File: ext/tinyformat/tinyformat.h" // tinyformat.h // Copyright (C) 2011, Chris Foster [chris42f (at) gmail (d0t) com] // // Boost Software License - Version 1.0 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //------------------------------------------------------------------------------ // Tinyformat: A minimal type safe printf replacement // // tinyformat.h is a type safe printf replacement library in a single C++ // header file. Design goals include: // // * Type safety and extensibility for user defined types. // * C99 printf() compatibility, to the extent possible using std::ostream // * Simplicity and minimalism. A single header file to include and distribute // with your projects. // * Augment rather than replace the standard stream formatting mechanism // * C++98 support, with optional C++11 niceties // // // Main interface example usage // ---------------------------- // // To print a date to std::cout: // // std::string weekday = "Wednesday"; // const char* month = "July"; // size_t day = 27; // long hour = 14; // int min = 44; // // tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min); // // The strange types here emphasize the type safety of the interface; it is // possible to print a std::string using the "%s" conversion, and a // size_t using the "%d" conversion. A similar result could be achieved // using either of the tfm::format() functions. One prints on a user provided // stream: // // tfm::format(std::cerr, "%s, %s %d, %.2d:%.2d\n", // weekday, month, day, hour, min); // // The other returns a std::string: // // std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n", // weekday, month, day, hour, min); // std::cout << date; // // These are the three primary interface functions. There is also a // convenience function printfln() which appends a newline to the usual result // of printf() for super simple logging. // // // User defined format functions // ----------------------------- // // Simulating variadic templates in C++98 is pretty painful since it requires // writing out the same function for each desired number of arguments. To make // this bearable tinyformat comes with a set of macros which are used // internally to generate the API, but which may also be used in user code. // // The three macros TINYFORMAT_ARGTYPES(n), TINYFORMAT_VARARGS(n) and // TINYFORMAT_PASSARGS(n) will generate a list of n argument types, // type/name pairs and argument names respectively when called with an integer // n between 1 and 16. We can use these to define a macro which generates the // desired user defined function with n arguments. To generate all 16 user // defined function bodies, use the macro TINYFORMAT_FOREACH_ARGNUM. For an // example, see the implementation of printf() at the end of the source file. // // Sometimes it's useful to be able to pass a list of format arguments through // to a non-template function. The FormatList class is provided as a way to do // this by storing the argument list in a type-opaque way. Continuing the // example from above, we construct a FormatList using makeFormatList(): // // FormatListRef formatList = tfm::makeFormatList(weekday, month, day, hour, min); // // The format list can now be passed into any non-template function and used // via a call to the vformat() function: // // tfm::vformat(std::cout, "%s, %s %d, %.2d:%.2d\n", formatList); // // // Additional API information // -------------------------- // // Error handling: Define TINYFORMAT_ERROR to customize the error handling for // format strings which are unsupported or have the wrong number of format // specifiers (calls assert() by default). // // User defined types: Uses operator<< for user defined types by default. // Overload formatValue() for more control. #ifndef TINYFORMAT_H_INCLUDED #define TINYFORMAT_H_INCLUDED namespace tinyformat {} //------------------------------------------------------------------------------ // Config section. Customize to your liking! // Namespace alias to encourage brevity namespace tfm = tinyformat; // Error handling; calls assert() by default. // #define TINYFORMAT_ERROR(reasonString) your_error_handler(reasonString) // Define for C++11 variadic templates which make the code shorter & more // general. If you don't define this, C++11 support is autodetected below. #define TINYFORMAT_USE_VARIADIC_TEMPLATES //------------------------------------------------------------------------------ // Implementation details. #include #include #include #ifndef TINYFORMAT_ASSERT # include # define TINYFORMAT_ASSERT(cond) assert(cond) #endif #ifndef TINYFORMAT_ERROR # include # define TINYFORMAT_ERROR(reason) assert(0 && reason) #endif #if !defined(TINYFORMAT_USE_VARIADIC_TEMPLATES) && !defined(TINYFORMAT_NO_VARIADIC_TEMPLATES) # ifdef __GXX_EXPERIMENTAL_CXX0X__ # define TINYFORMAT_USE_VARIADIC_TEMPLATES # endif #endif #if defined(__GLIBCXX__) && __GLIBCXX__ < 20080201 // std::showpos is broken on old libstdc++ as provided with OSX. See // http://gcc.gnu.org/ml/libstdc++/2007-11/msg00075.html # define TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND #endif #ifdef __APPLE__ // Workaround OSX linker warning: xcode uses different default symbol // visibilities for static libs vs executables (see issue #25) # define TINYFORMAT_HIDDEN __attribute__((visibility("hidden"))) #else # define TINYFORMAT_HIDDEN #endif namespace tinyformat { //------------------------------------------------------------------------------ namespace detail { // Test whether type T1 is convertible to type T2 template struct is_convertible { private: // two types of different size struct fail { char dummy[2]; }; struct succeed { char dummy; }; // Try to convert a T1 to a T2 by plugging into tryConvert static fail tryConvert(...); static succeed tryConvert(const T2&); static const T1& makeT1(); public: # ifdef _MSC_VER // Disable spurious loss of precision warnings in tryConvert(makeT1()) # pragma warning(push) # pragma warning(disable:4244) # pragma warning(disable:4267) # endif // Standard trick: the (...) version of tryConvert will be chosen from // the overload set only if the version taking a T2 doesn't match. // Then we compare the sizes of the return types to check which // function matched. Very neat, in a disgusting kind of way :) static const bool value = sizeof(tryConvert(makeT1())) == sizeof(succeed); # ifdef _MSC_VER # pragma warning(pop) # endif }; // Detect when a type is not a wchar_t string template struct is_wchar { typedef int tinyformat_wchar_is_not_supported; }; template<> struct is_wchar {}; template<> struct is_wchar {}; template struct is_wchar {}; template struct is_wchar {}; // Format the value by casting to type fmtT. This default implementation // should never be called. template::value> struct formatValueAsType { static void invoke(std::ostream& /*out*/, const T& /*value*/) { TINYFORMAT_ASSERT(0); } }; // Specialized version for types that can actually be converted to fmtT, as // indicated by the "convertible" template parameter. template struct formatValueAsType { static void invoke(std::ostream& out, const T& value) { out << static_cast(value); } }; #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND template::value> struct formatZeroIntegerWorkaround { static bool invoke(std::ostream& /**/, const T& /**/) { return false; } }; template struct formatZeroIntegerWorkaround { static bool invoke(std::ostream& out, const T& value) { if (static_cast(value) == 0 && out.flags() & std::ios::showpos) { out << "+0"; return true; } return false; } }; #endif // TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND // Convert an arbitrary type to integer. The version with convertible=false // throws an error. template::value> struct convertToInt { static int invoke(const T& /*value*/) { TINYFORMAT_ERROR("tinyformat: Cannot convert from argument type to " "integer for use as variable width or precision"); return 0; } }; // Specialization for convertToInt when conversion is possible template struct convertToInt { static int invoke(const T& value) { return static_cast(value); } }; // Format at most ntrunc characters to the given stream. template inline void formatTruncated(std::ostream& out, const T& value, int ntrunc) { std::ostringstream tmp; tmp << value; std::string result = tmp.str(); out.write(result.c_str(), (std::min)(ntrunc, static_cast(result.size()))); } #define TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(type) \ inline void formatTruncated(std::ostream& out, type* value, int ntrunc) \ { \ std::streamsize len = 0; \ while(len < ntrunc && value[len] != 0) \ ++len; \ out.write(value, len); \ } // Overload for const char* and char*. Could overload for signed & unsigned // char too, but these are technically unneeded for printf compatibility. TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(const char) TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(char) #undef TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR } // namespace detail //------------------------------------------------------------------------------ // Variable formatting functions. May be overridden for user-defined types if // desired. /// Format a value into a stream, delegating to operator<< by default. /// /// Users may override this for their own types. When this function is called, /// the stream flags will have been modified according to the format string. /// The format specification is provided in the range [fmtBegin, fmtEnd). For /// truncating conversions, ntrunc is set to the desired maximum number of /// characters, for example "%.7s" calls formatValue with ntrunc = 7. /// /// By default, formatValue() uses the usual stream insertion operator /// operator<< to format the type T, with special cases for the %c and %p /// conversions. template inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, const char* fmtEnd, int ntrunc, const T& value) { #ifndef TINYFORMAT_ALLOW_WCHAR_STRINGS // Since we don't support printing of wchar_t using "%ls", make it fail at // compile time in preference to printing as a void* at runtime. typedef typename detail::is_wchar::tinyformat_wchar_is_not_supported DummyType; (void) DummyType(); // avoid unused type warning with gcc-4.8 #endif // The mess here is to support the %c and %p conversions: if these // conversions are active we try to convert the type to a char or const // void* respectively and format that instead of the value itself. For the // %p conversion it's important to avoid dereferencing the pointer, which // could otherwise lead to a crash when printing a dangling (const char*). const bool canConvertToChar = detail::is_convertible::value; const bool canConvertToVoidPtr = detail::is_convertible::value; if(canConvertToChar && *(fmtEnd-1) == 'c') detail::formatValueAsType::invoke(out, value); else if(canConvertToVoidPtr && *(fmtEnd-1) == 'p') detail::formatValueAsType::invoke(out, value); #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND else if(detail::formatZeroIntegerWorkaround::invoke(out, value)) /**/; #endif else if(ntrunc >= 0) { // Take care not to overread C strings in truncating conversions like // "%.4s" where at most 4 characters may be read. detail::formatTruncated(out, value, ntrunc); } else out << value; } // Overloaded version for char types to support printing as an integer #define TINYFORMAT_DEFINE_FORMATVALUE_CHAR(charType) \ inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, \ const char* fmtEnd, int /**/, charType value) \ { \ switch(*(fmtEnd-1)) \ { \ case 'u': case 'd': case 'i': case 'o': case 'X': case 'x': \ out << static_cast(value); break; \ default: \ out << value; break; \ } \ } // per 3.9.1: char, signed char and unsigned char are all distinct types TINYFORMAT_DEFINE_FORMATVALUE_CHAR(char) TINYFORMAT_DEFINE_FORMATVALUE_CHAR(signed char) TINYFORMAT_DEFINE_FORMATVALUE_CHAR(unsigned char) #undef TINYFORMAT_DEFINE_FORMATVALUE_CHAR //------------------------------------------------------------------------------ // Tools for emulating variadic templates in C++98. The basic idea here is // stolen from the boost preprocessor metaprogramming library and cut down to // be just general enough for what we need. #define TINYFORMAT_ARGTYPES(n) TINYFORMAT_ARGTYPES_ ## n #define TINYFORMAT_VARARGS(n) TINYFORMAT_VARARGS_ ## n #define TINYFORMAT_PASSARGS(n) TINYFORMAT_PASSARGS_ ## n #define TINYFORMAT_PASSARGS_TAIL(n) TINYFORMAT_PASSARGS_TAIL_ ## n // To keep it as transparent as possible, the macros below have been generated // using python via the excellent cog.py code generation script. This avoids // the need for a bunch of complex (but more general) preprocessor tricks as // used in boost.preprocessor. // // To rerun the code generation in place, use `cog.py -r tinyformat.h` // (see http://nedbatchelder.com/code/cog). Alternatively you can just create // extra versions by hand. /*[[[cog maxParams = 16 def makeCommaSepLists(lineTemplate, elemTemplate, startInd=1): for j in range(startInd,maxParams+1): list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)]) cog.outl(lineTemplate % {'j':j, 'list':list}) makeCommaSepLists('#define TINYFORMAT_ARGTYPES_%(j)d %(list)s', 'class T%(i)d') cog.outl() makeCommaSepLists('#define TINYFORMAT_VARARGS_%(j)d %(list)s', 'const T%(i)d& v%(i)d') cog.outl() makeCommaSepLists('#define TINYFORMAT_PASSARGS_%(j)d %(list)s', 'v%(i)d') cog.outl() cog.outl('#define TINYFORMAT_PASSARGS_TAIL_1') makeCommaSepLists('#define TINYFORMAT_PASSARGS_TAIL_%(j)d , %(list)s', 'v%(i)d', startInd = 2) cog.outl() cog.outl('#define TINYFORMAT_FOREACH_ARGNUM(m) \\\n ' + ' '.join(['m(%d)' % (j,) for j in range(1,maxParams+1)])) ]]]*/ #define TINYFORMAT_ARGTYPES_1 class T1 #define TINYFORMAT_ARGTYPES_2 class T1, class T2 #define TINYFORMAT_ARGTYPES_3 class T1, class T2, class T3 #define TINYFORMAT_ARGTYPES_4 class T1, class T2, class T3, class T4 #define TINYFORMAT_ARGTYPES_5 class T1, class T2, class T3, class T4, class T5 #define TINYFORMAT_ARGTYPES_6 class T1, class T2, class T3, class T4, class T5, class T6 #define TINYFORMAT_ARGTYPES_7 class T1, class T2, class T3, class T4, class T5, class T6, class T7 #define TINYFORMAT_ARGTYPES_8 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8 #define TINYFORMAT_ARGTYPES_9 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9 #define TINYFORMAT_ARGTYPES_10 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10 #define TINYFORMAT_ARGTYPES_11 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11 #define TINYFORMAT_ARGTYPES_12 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12 #define TINYFORMAT_ARGTYPES_13 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13 #define TINYFORMAT_ARGTYPES_14 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14 #define TINYFORMAT_ARGTYPES_15 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15 #define TINYFORMAT_ARGTYPES_16 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16 #define TINYFORMAT_VARARGS_1 const T1& v1 #define TINYFORMAT_VARARGS_2 const T1& v1, const T2& v2 #define TINYFORMAT_VARARGS_3 const T1& v1, const T2& v2, const T3& v3 #define TINYFORMAT_VARARGS_4 const T1& v1, const T2& v2, const T3& v3, const T4& v4 #define TINYFORMAT_VARARGS_5 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5 #define TINYFORMAT_VARARGS_6 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6 #define TINYFORMAT_VARARGS_7 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7 #define TINYFORMAT_VARARGS_8 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8 #define TINYFORMAT_VARARGS_9 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9 #define TINYFORMAT_VARARGS_10 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10 #define TINYFORMAT_VARARGS_11 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11 #define TINYFORMAT_VARARGS_12 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12 #define TINYFORMAT_VARARGS_13 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13 #define TINYFORMAT_VARARGS_14 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14 #define TINYFORMAT_VARARGS_15 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14, const T15& v15 #define TINYFORMAT_VARARGS_16 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14, const T15& v15, const T16& v16 #define TINYFORMAT_PASSARGS_1 v1 #define TINYFORMAT_PASSARGS_2 v1, v2 #define TINYFORMAT_PASSARGS_3 v1, v2, v3 #define TINYFORMAT_PASSARGS_4 v1, v2, v3, v4 #define TINYFORMAT_PASSARGS_5 v1, v2, v3, v4, v5 #define TINYFORMAT_PASSARGS_6 v1, v2, v3, v4, v5, v6 #define TINYFORMAT_PASSARGS_7 v1, v2, v3, v4, v5, v6, v7 #define TINYFORMAT_PASSARGS_8 v1, v2, v3, v4, v5, v6, v7, v8 #define TINYFORMAT_PASSARGS_9 v1, v2, v3, v4, v5, v6, v7, v8, v9 #define TINYFORMAT_PASSARGS_10 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 #define TINYFORMAT_PASSARGS_11 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 #define TINYFORMAT_PASSARGS_12 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 #define TINYFORMAT_PASSARGS_13 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13 #define TINYFORMAT_PASSARGS_14 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14 #define TINYFORMAT_PASSARGS_15 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 #define TINYFORMAT_PASSARGS_16 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16 #define TINYFORMAT_PASSARGS_TAIL_1 #define TINYFORMAT_PASSARGS_TAIL_2 , v2 #define TINYFORMAT_PASSARGS_TAIL_3 , v2, v3 #define TINYFORMAT_PASSARGS_TAIL_4 , v2, v3, v4 #define TINYFORMAT_PASSARGS_TAIL_5 , v2, v3, v4, v5 #define TINYFORMAT_PASSARGS_TAIL_6 , v2, v3, v4, v5, v6 #define TINYFORMAT_PASSARGS_TAIL_7 , v2, v3, v4, v5, v6, v7 #define TINYFORMAT_PASSARGS_TAIL_8 , v2, v3, v4, v5, v6, v7, v8 #define TINYFORMAT_PASSARGS_TAIL_9 , v2, v3, v4, v5, v6, v7, v8, v9 #define TINYFORMAT_PASSARGS_TAIL_10 , v2, v3, v4, v5, v6, v7, v8, v9, v10 #define TINYFORMAT_PASSARGS_TAIL_11 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11 #define TINYFORMAT_PASSARGS_TAIL_12 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12 #define TINYFORMAT_PASSARGS_TAIL_13 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13 #define TINYFORMAT_PASSARGS_TAIL_14 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14 #define TINYFORMAT_PASSARGS_TAIL_15 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 #define TINYFORMAT_PASSARGS_TAIL_16 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16 #define TINYFORMAT_FOREACH_ARGNUM(m) \ m(1) m(2) m(3) m(4) m(5) m(6) m(7) m(8) m(9) m(10) m(11) m(12) m(13) m(14) m(15) m(16) //[[[end]]] namespace detail { // Type-opaque holder for an argument to format(), with associated actions on // the type held as explicit function pointers. This allows FormatArg's for // each argument to be allocated as a homogenous array inside FormatList // whereas a naive implementation based on inheritance does not. class FormatArg { public: FormatArg() : m_value(NULL), m_formatImpl(NULL), m_toIntImpl(NULL) { } template FormatArg(const T& value) : m_value(static_cast(&value)), m_formatImpl(&formatImpl), m_toIntImpl(&toIntImpl) { } void format(std::ostream& out, const char* fmtBegin, const char* fmtEnd, int ntrunc) const { TINYFORMAT_ASSERT(m_value); TINYFORMAT_ASSERT(m_formatImpl); m_formatImpl(out, fmtBegin, fmtEnd, ntrunc, m_value); } int toInt() const { TINYFORMAT_ASSERT(m_value); TINYFORMAT_ASSERT(m_toIntImpl); return m_toIntImpl(m_value); } private: template TINYFORMAT_HIDDEN static void formatImpl(std::ostream& out, const char* fmtBegin, const char* fmtEnd, int ntrunc, const void* value) { formatValue(out, fmtBegin, fmtEnd, ntrunc, *static_cast(value)); } template TINYFORMAT_HIDDEN static int toIntImpl(const void* value) { return convertToInt::invoke(*static_cast(value)); } const void* m_value; void (*m_formatImpl)(std::ostream& out, const char* fmtBegin, const char* fmtEnd, int ntrunc, const void* value); int (*m_toIntImpl)(const void* value); }; // Parse and return an integer from the string c, as atoi() // On return, c is set to one past the end of the integer. inline int parseIntAndAdvance(const char*& c) { int i = 0; for(;*c >= '0' && *c <= '9'; ++c) i = 10*i + (*c - '0'); return i; } // Print literal part of format string and return next format spec // position. // // Skips over any occurrences of '%%', printing a literal '%' to the // output. The position of the first % character of the next // nontrivial format spec is returned, or the end of string. inline const char* printFormatStringLiteral(std::ostream& out, const char* fmt) { const char* c = fmt; for(;; ++c) { switch(*c) { case '\0': out.write(fmt, c - fmt); return c; case '%': out.write(fmt, c - fmt); if(*(c+1) != '%') return c; // for "%%", tack trailing % onto next literal section. fmt = ++c; break; default: break; } } } // Parse a format string and set the stream state accordingly. // // The format mini-language recognized here is meant to be the one from C99, // with the form "%[flags][width][.precision][length]type". // // Formatting options which can't be natively represented using the ostream // state are returned in spacePadPositive (for space padded positive numbers) // and ntrunc (for truncating conversions). argIndex is incremented if // necessary to pull out variable width and precision . The function returns a // pointer to the character after the end of the current format spec. inline const char* streamStateFromFormat(std::ostream& out, bool& spacePadPositive, int& ntrunc, const char* fmtStart, const detail::FormatArg* formatters, int& argIndex, int numFormatters) { if(*fmtStart != '%') { TINYFORMAT_ERROR("tinyformat: Not enough conversion specifiers in format string"); return fmtStart; } // Reset stream state to defaults. out.width(0); out.precision(6); out.fill(' '); // Reset most flags; ignore irrelevant unitbuf & skipws. out.unsetf(std::ios::adjustfield | std::ios::basefield | std::ios::floatfield | std::ios::showbase | std::ios::boolalpha | std::ios::showpoint | std::ios::showpos | std::ios::uppercase); bool precisionSet = false; bool widthSet = false; int widthExtra = 0; const char* c = fmtStart + 1; // 1) Parse flags for(;; ++c) { switch(*c) { case '#': out.setf(std::ios::showpoint | std::ios::showbase); continue; case '0': // overridden by left alignment ('-' flag) if(!(out.flags() & std::ios::left)) { // Use internal padding so that numeric values are // formatted correctly, eg -00010 rather than 000-10 out.fill('0'); out.setf(std::ios::internal, std::ios::adjustfield); } continue; case '-': out.fill(' '); out.setf(std::ios::left, std::ios::adjustfield); continue; case ' ': // overridden by show positive sign, '+' flag. if(!(out.flags() & std::ios::showpos)) spacePadPositive = true; continue; case '+': out.setf(std::ios::showpos); spacePadPositive = false; widthExtra = 1; continue; default: break; } break; } // 2) Parse width if(*c >= '0' && *c <= '9') { widthSet = true; out.width(parseIntAndAdvance(c)); } if(*c == '*') { widthSet = true; int width = 0; if(argIndex < numFormatters) width = formatters[argIndex++].toInt(); else TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable width"); if(width < 0) { // negative widths correspond to '-' flag set out.fill(' '); out.setf(std::ios::left, std::ios::adjustfield); width = -width; } out.width(width); ++c; } // 3) Parse precision if(*c == '.') { ++c; int precision = 0; if(*c == '*') { ++c; if(argIndex < numFormatters) precision = formatters[argIndex++].toInt(); else TINYFORMAT_ERROR("tinyformat: Not enough arguments to read variable precision"); } else { if(*c >= '0' && *c <= '9') precision = parseIntAndAdvance(c); else if(*c == '-') // negative precisions ignored, treated as zero. parseIntAndAdvance(++c); } out.precision(precision); precisionSet = true; } // 4) Ignore any C99 length modifier while(*c == 'l' || *c == 'h' || *c == 'L' || *c == 'j' || *c == 'z' || *c == 't') ++c; // 5) We're up to the conversion specifier character. // Set stream flags based on conversion specifier (thanks to the // boost::format class for forging the way here). bool intConversion = false; switch(*c) { case 'u': case 'd': case 'i': out.setf(std::ios::dec, std::ios::basefield); intConversion = true; break; case 'o': out.setf(std::ios::oct, std::ios::basefield); intConversion = true; break; case 'X': out.setf(std::ios::uppercase); [[fallthrough]]; // Falls through case 'x': case 'p': out.setf(std::ios::hex, std::ios::basefield); intConversion = true; break; case 'E': out.setf(std::ios::uppercase); [[fallthrough]]; // Falls through case 'e': out.setf(std::ios::scientific, std::ios::floatfield); out.setf(std::ios::dec, std::ios::basefield); break; case 'F': out.setf(std::ios::uppercase); [[fallthrough]]; // Falls through case 'f': out.setf(std::ios::fixed, std::ios::floatfield); break; case 'G': out.setf(std::ios::uppercase); [[fallthrough]]; // Falls through case 'g': out.setf(std::ios::dec, std::ios::basefield); // As in boost::format, let stream decide float format. out.flags(out.flags() & ~std::ios::floatfield); break; case 'a': case 'A': TINYFORMAT_ERROR("tinyformat: the %a and %A conversion specs " "are not supported"); break; case 'c': // Handled as special case inside formatValue() break; case 's': if(precisionSet) ntrunc = static_cast(out.precision()); // Make %s print booleans as "true" and "false" out.setf(std::ios::boolalpha); break; case 'n': // Not supported - will cause problems! TINYFORMAT_ERROR("tinyformat: %n conversion spec not supported"); break; case '\0': TINYFORMAT_ERROR("tinyformat: Conversion spec incorrectly " "terminated by end of string"); return c; default: break; } if(intConversion && precisionSet && !widthSet) { // "precision" for integers gives the minimum number of digits (to be // padded with zeros on the left). This isn't really supported by the // iostreams, but we can approximately simulate it with the width if // the width isn't otherwise used. out.width(out.precision() + widthExtra); out.setf(std::ios::internal, std::ios::adjustfield); out.fill('0'); } return c+1; } //------------------------------------------------------------------------------ inline void formatImpl(std::ostream& out, const char* fmt, const detail::FormatArg* formatters, int numFormatters) { // Saved stream state std::streamsize origWidth = out.width(); std::streamsize origPrecision = out.precision(); std::ios::fmtflags origFlags = out.flags(); char origFill = out.fill(); for (int argIndex = 0; argIndex < numFormatters; ++argIndex) { // Parse the format string fmt = printFormatStringLiteral(out, fmt); bool spacePadPositive = false; int ntrunc = -1; const char* fmtEnd = streamStateFromFormat(out, spacePadPositive, ntrunc, fmt, formatters, argIndex, numFormatters); if (argIndex >= numFormatters) { // Check args remain after reading any variable width/precision TINYFORMAT_ERROR("tinyformat: Not enough format arguments"); return; } const FormatArg& arg = formatters[argIndex]; // Format the arg into the stream. if(!spacePadPositive) arg.format(out, fmt, fmtEnd, ntrunc); else { // The following is a special case with no direct correspondence // between stream formatting and the printf() behaviour. Simulate // it crudely by formatting into a temporary string stream and // munging the resulting string. std::ostringstream tmpStream; tmpStream.copyfmt(out); tmpStream.setf(std::ios::showpos); arg.format(tmpStream, fmt, fmtEnd, ntrunc); std::string result = tmpStream.str(); // allocates... yuck. for(size_t i = 0, iend = result.size(); i < iend; ++i) if(result[i] == '+') result[i] = ' '; out << result; } fmt = fmtEnd; } // Print remaining part of format string. fmt = printFormatStringLiteral(out, fmt); if(*fmt != '\0') TINYFORMAT_ERROR("tinyformat: Too many conversion specifiers in format string"); // Restore stream state out.width(origWidth); out.precision(origPrecision); out.flags(origFlags); out.fill(origFill); } } // namespace detail /// List of template arguments format(), held in a type-opaque way. /// /// A const reference to FormatList (typedef'd as FormatListRef) may be /// conveniently used to pass arguments to non-template functions: All type /// information has been stripped from the arguments, leaving just enough of a /// common interface to perform formatting as required. class FormatList { public: FormatList(detail::FormatArg* formatters, int N) : m_formatters(formatters), m_N(N) { } friend void vformat(std::ostream& out, const char* fmt, const FormatList& list); private: const detail::FormatArg* m_formatters; int m_N; }; /// Reference to type-opaque format list for passing to vformat() typedef const FormatList& FormatListRef; namespace detail { // Format list subclass with fixed storage to avoid dynamic allocation template class FormatListN : public FormatList { public: #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES template FormatListN(const Args&... args) : FormatList(&m_formatterStore[0], N), m_formatterStore { FormatArg(args)... } { static_assert(sizeof...(args) == N, "Number of args must be N"); } #else // C++98 version void init(int) {} # define TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR(n) \ \ template \ FormatListN(TINYFORMAT_VARARGS(n)) \ : FormatList(&m_formatterStore[0], n) \ { TINYFORMAT_ASSERT(n == N); init(0, TINYFORMAT_PASSARGS(n)); } \ \ template \ void init(int i, TINYFORMAT_VARARGS(n)) \ { \ m_formatterStore[i] = FormatArg(v1); \ init(i+1 TINYFORMAT_PASSARGS_TAIL(n)); \ } TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR) # undef TINYFORMAT_MAKE_FORMATLIST_CONSTRUCTOR #endif private: FormatArg m_formatterStore[N]; }; // Special 0-arg version - MSVC says zero-sized C array in struct is nonstandard template<> class FormatListN<0> : public FormatList { public: FormatListN() : FormatList(0, 0) {} }; } // namespace detail //------------------------------------------------------------------------------ // Primary API functions #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES /// Make type-agnostic format list from list of template arguments. /// /// The exact return type of this function is an implementation detail and /// shouldn't be relied upon. Instead it should be stored as a FormatListRef: /// /// FormatListRef formatList = makeFormatList( /*...*/ ); template detail::FormatListN makeFormatList(const Args&... args) { return detail::FormatListN(args...); } #else // C++98 version inline detail::FormatListN<0> makeFormatList() { return detail::FormatListN<0>(); } #define TINYFORMAT_MAKE_MAKEFORMATLIST(n) \ template \ detail::FormatListN makeFormatList(TINYFORMAT_VARARGS(n)) \ { \ return detail::FormatListN(TINYFORMAT_PASSARGS(n)); \ } TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_MAKEFORMATLIST) #undef TINYFORMAT_MAKE_MAKEFORMATLIST #endif /// Format list of arguments to the stream according to the given format string. /// /// The name vformat() is chosen for the semantic similarity to vprintf(): the /// list of format arguments is held in a single function argument. inline void vformat(std::ostream& out, const char* fmt, FormatListRef list) { detail::formatImpl(out, fmt, list.m_formatters, list.m_N); } #ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES /// Format list of arguments to the stream according to given format string. template void format(std::ostream& out, const char* fmt, const Args&... args) { vformat(out, fmt, makeFormatList(args...)); } /// Format list of arguments according to the given format string and return /// the result as a string. template std::string format(const char* fmt, const Args&... args) { std::ostringstream oss; format(oss, fmt, args...); return oss.str(); } /// Format list of arguments to std::cout, according to the given format string template void printf(const char* fmt, const Args&... args) { format(std::cout, fmt, args...); } template void printfln(const char* fmt, const Args&... args) { format(std::cout, fmt, args...); std::cout << '\n'; } #else // C++98 version inline void format(std::ostream& out, const char* fmt) { vformat(out, fmt, makeFormatList()); } inline std::string format(const char* fmt) { std::ostringstream oss; format(oss, fmt); return oss.str(); } inline void printf(const char* fmt) { format(std::cout, fmt); } inline void printfln(const char* fmt) { format(std::cout, fmt); std::cout << '\n'; } #define TINYFORMAT_MAKE_FORMAT_FUNCS(n) \ \ template \ void format(std::ostream& out, const char* fmt, TINYFORMAT_VARARGS(n)) \ { \ vformat(out, fmt, makeFormatList(TINYFORMAT_PASSARGS(n))); \ } \ \ template \ std::string format(const char* fmt, TINYFORMAT_VARARGS(n)) \ { \ std::ostringstream oss; \ format(oss, fmt, TINYFORMAT_PASSARGS(n)); \ return oss.str(); \ } \ \ template \ void printf(const char* fmt, TINYFORMAT_VARARGS(n)) \ { \ format(std::cout, fmt, TINYFORMAT_PASSARGS(n)); \ } \ \ template \ void printfln(const char* fmt, TINYFORMAT_VARARGS(n)) \ { \ format(std::cout, fmt, TINYFORMAT_PASSARGS(n)); \ std::cout << '\n'; \ } TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_FUNCS) #undef TINYFORMAT_MAKE_FORMAT_FUNCS #endif } // namespace tinyformat #endif // TINYFORMAT_H_INCLUDED #pragma region "File: Core/Types.h" #include #include #include class Identifier { public: explicit Identifier() = default; explicit Identifier(std::string name); Identifier(const Identifier &) = default; Identifier(Identifier &&) = default; Identifier &operator=(const Identifier &) = default; Identifier &operator=(Identifier &&) = default; size_t size() const { return _name.size(); } bool startsWith(char value) const { return _name.front() == value; } bool startsWith(std::string_view value) const { if (_name.size() < value.size()) return false; return memcmp(_name.data(), value.data(), value.size()) == 0; } const std::string &string() const { return _name; } bool operator<(const Identifier& other) const { return _name < other._name; } bool operator==(const Identifier& other) const { return _name == other._name; } bool operator!=(const Identifier& other) const { return _name != other._name; } bool operator==(const std::string_view other) const { return _name == other; } bool operator!=(const std::string_view other) const { return _name != other; } private: std::string _name; }; inline bool operator==(const std::string_view first, const Identifier &second) { return second == first; } inline bool operator!=(const std::string_view first, const Identifier &second) { return second != first; } std::ostream& operator<<(std::ostream &output, const Identifier &identifier); class StringLiteral { public: StringLiteral() = default; StringLiteral(std::string value); StringLiteral(const StringLiteral &) = default; StringLiteral(StringLiteral &&) = default; StringLiteral &operator=(const StringLiteral &) = default; StringLiteral &operator=(StringLiteral &&) = default; size_t size() const { return _value.size(); } const std::string &string() const { return _value; } fs::path path() const { return fs::u8path(_value); } StringLiteral operator+(const StringLiteral &other) const; bool operator==(const StringLiteral &other) const; bool operator!=(const StringLiteral &other) const; bool operator<(const StringLiteral &other) const; bool operator<=(const StringLiteral &other) const; bool operator>(const StringLiteral &other) const; bool operator>=(const StringLiteral &other) const; private: std::string _value; }; std::ostream& operator<<(std::ostream &output, const StringLiteral &string); #pragma region "File: Core/Types.cpp" Identifier::Identifier(std::string name) : _name(std::move(name)) { } std::ostream &operator<<(std::ostream &output, const Identifier &identifier) { output << identifier.string(); return output; } StringLiteral::StringLiteral(std::string value) : _value(std::move(value)) { } StringLiteral StringLiteral::operator+(const StringLiteral &other) const { return StringLiteral(_value + other._value); } bool StringLiteral::operator==(const StringLiteral &other) const { return _value == other._value; } bool StringLiteral::operator!=(const StringLiteral &other) const { return _value != other._value; } bool StringLiteral::operator<(const StringLiteral &other) const { return _value < other._value; } bool StringLiteral::operator<=(const StringLiteral &other) const { return _value <= other._value; } bool StringLiteral::operator>(const StringLiteral &other) const { return _value > other._value; } bool StringLiteral::operator>=(const StringLiteral &other) const { return _value >= other._value; } std::ostream &operator<<(std::ostream &output, const StringLiteral &value) { output << value.string(); return output; } #pragma region "File: Commands/CAssemblerCommand.h" class TempData; class SymbolData; struct ValidateState { bool noFileChange = false; const char *noFileChangeDirective = nullptr; int passes = 0; }; class CAssemblerCommand { public: CAssemblerCommand(); virtual ~CAssemblerCommand() { }; virtual bool Validate(const ValidateState &state) = 0; virtual void Encode() const = 0; virtual void writeTempData(TempData& tempData) const = 0; virtual void writeSymData(SymbolData& symData) const { }; void applyFileInfo(); int getSection() { return section; } void updateSection(int num) { section = num; } protected: int FileNum; int FileLine; private: int section; }; class DummyCommand: public CAssemblerCommand { public: bool Validate(const ValidateState &state) override { return false; } void Encode() const override { }; void writeTempData(TempData& tempData) const override { }; void writeSymData(SymbolData& symData) const override { }; }; class InvalidCommand: public CAssemblerCommand { public: bool Validate(const ValidateState &state) override { return false; } void Encode() const override { }; void writeTempData(TempData& tempData) const override { }; void writeSymData(SymbolData& symData) const override { }; }; #pragma region "File: Core/Expression.h" #include #include #include #include #include class Label; struct ExpressionFunctionEntry; struct ExpressionLabelFunctionEntry; enum class OperatorType { Invalid, Integer, Float, Identifier, String, MemoryPos, Add, Sub, Mult, Div, Mod, Neg, LogNot, BitNot, LeftShift, RightShift, Less, Greater, LessEqual, GreaterEqual, Equal, NotEqual, BitAnd, Xor, BitOr, LogAnd, LogOr, TertiaryIf, ToString, FunctionCall }; enum class ExpressionValueType { Invalid, Integer, Float, String }; struct ExpressionValue { ExpressionValueType type; ExpressionValue() { type = ExpressionValueType::Invalid; intValue = 0; } ExpressionValue(int64_t value) { type = ExpressionValueType::Integer; intValue = value; } ExpressionValue(double value) { type = ExpressionValueType::Float; floatValue = value; } ExpressionValue(const StringLiteral& value) : type(ExpressionValueType::String), strValue(value) { intValue = 0; } bool isFloat() const { return type == ExpressionValueType::Float; } bool isInt() const { return type == ExpressionValueType::Integer; } bool isString() const { return type == ExpressionValueType::String; } bool isValid() const { return type != ExpressionValueType::Invalid; } union { int64_t intValue; double floatValue; }; StringLiteral strValue; ExpressionValue operator!() const; ExpressionValue operator~() const; bool operator<(const ExpressionValue& other) const; bool operator<=(const ExpressionValue& other) const; bool operator>(const ExpressionValue& other) const; bool operator>=(const ExpressionValue& other) const; bool operator==(const ExpressionValue& other) const; bool operator!=(const ExpressionValue& other) const; ExpressionValue operator+(const ExpressionValue& other) const; ExpressionValue operator-(const ExpressionValue& other) const; ExpressionValue operator*(const ExpressionValue& other) const; ExpressionValue operator/(const ExpressionValue& other) const; ExpressionValue operator%(const ExpressionValue& other) const; ExpressionValue operator<<(const ExpressionValue& other) const; ExpressionValue operator>>(const ExpressionValue& other) const; ExpressionValue operator&(const ExpressionValue& other) const; ExpressionValue operator|(const ExpressionValue& other) const; ExpressionValue operator&&(const ExpressionValue& other) const; ExpressionValue operator||(const ExpressionValue& other) const; ExpressionValue operator^(const ExpressionValue& other) const; }; class ExpressionInternal { public: ExpressionInternal() = default; ~ExpressionInternal() = default; ExpressionInternal(int64_t value); ExpressionInternal(double value); ExpressionInternal(Identifier value); ExpressionInternal(StringLiteral value); template ExpressionInternal(OperatorType op, ARGS... parameters) : type(op) { ( children.push_back(std::move(parameters)), ... ); } ExpressionInternal(const Identifier& name, std::vector> parameters); ExpressionValue evaluate(); std::string toString(); bool isIdentifier() { return type == OperatorType::Identifier; } const Identifier &getIdentifier() { return valueAs(); } void replaceMemoryPos(const Identifier& identifierName); bool simplify(bool inUnknownOrFalseBlock); unsigned int getFileNum() { return fileNum; } unsigned int getSection() { return section; } private: using ValueTypes = std::variant; template const T &valueAs() const { assert(std::holds_alternative(value)); return *std::get_if(&value); } std::string formatFunctionCall(); ExpressionValue executeFunctionCall(); OperatorType type = OperatorType::Invalid; std::vector> children; ValueTypes value; unsigned int fileNum, section; }; class Expression { public: Expression() = default; Expression(std::unique_ptr exp, bool inUnknownOrFalseBlock); ExpressionValue evaluate(); bool isLoaded() const { return expression != nullptr; } void replaceMemoryPos(const Identifier& identifierName); bool isConstExpression() { return constExpression; } template bool evaluateInteger(T& dest) { if (expression == nullptr) return false; ExpressionValue value = expression->evaluate(); if (value.isInt() == false) return false; dest = (T) value.intValue; return true; } bool evaluateString(StringLiteral& dest, bool convert); bool evaluateIdentifier(Identifier& dest); std::string toString(); private: std::shared_ptr expression; bool constExpression = true; }; Expression createConstExpression(int64_t value); #pragma region "File: Parser/Tokenizer.h" #include #include #include #include #include class TextFile; enum class TokenType { Invalid, Identifier, Integer, String, Float, LParen, RParen, Plus, Minus, Mult, Div, Mod, Caret, Tilde, LeftShift, RightShift, Less, Greater, LessEqual, GreaterEqual, Equal, NotEqual, BitAnd, BitOr, LogAnd, LogOr, Exclamation, Question, Colon, LBrack, RBrack, Comma, Assign, Equ, EquValue, Hash, LBrace, RBrace, Dollar, NumberString, Degree, Separator }; struct Token { friend class Tokenizer; const std::string &getOriginalText() const { return originalText; } template void setValue(T value, std::string originalText) { this->value = std::move(value); this->originalText = std::move(originalText); } const Identifier &identifierValue() const { assert(std::holds_alternative(value)); return *std::get_if(&value); } const StringLiteral &stringValue() const { assert(std::holds_alternative(value)); return *std::get_if(&value); } int64_t intValue() const { assert(std::holds_alternative(value)); return *std::get_if(&value); } double floatValue() const { assert(std::holds_alternative(value)); return *std::get_if(&value); } size_t line = 0; size_t column = 0; TokenType type = TokenType::Invalid; protected: bool checked = false; using ValueType = std::variant; ValueType value; std::string originalText; }; typedef std::list TokenList; struct TokenizerPosition { friend class Tokenizer; TokenizerPosition previous() { TokenizerPosition pos = *this; --pos.it; return pos; } private: TokenList::iterator it; }; class Tokenizer { public: Tokenizer(); const Token& nextToken(); const Token& peekToken(int ahead = 0); void eatToken() { eatTokens(1); } void eatTokens(int num); bool atEnd() { return position.it == tokens.end(); } TokenizerPosition getPosition() { return position; } void setPosition(TokenizerPosition pos) { position = pos; } void skipLookahead(); std::vector getTokens(TokenizerPosition start, TokenizerPosition end) const; void registerReplacement(const Identifier& identifier, std::vector& tokens); void registerReplacement(const Identifier& identifier, const std::string& newValue); void registerReplacementString(const Identifier& identifier, const StringLiteral& newValue); void registerReplacementInteger(const Identifier& identifier, int64_t newValue); void registerReplacementFloat(const Identifier& identifier, double newValue); static size_t addEquValue(const std::vector& tokens); static void clearEquValues() { equValues.clear(); } void resetLookaheadCheckMarks(); protected: void clearTokens() { tokens.clear(); }; void resetPosition() { position.it = tokens.begin(); } void addToken(Token token); private: bool processElement(TokenList::iterator& it); TokenList tokens; TokenizerPosition position; struct Replacement { Identifier identifier; std::vector value; }; Token invalidToken; std::vector replacements; static std::vector> equValues; }; class FileTokenizer: public Tokenizer { public: bool init(TextFile* input); protected: Token loadToken(); bool isInputAtEnd(); void skipWhitespace(); void createToken(TokenType type, size_t length); void createToken(TokenType type, size_t length, int64_t value); void createToken(TokenType type, size_t length, double value); void createToken(TokenType type, size_t length, const std::string& value); void createToken(TokenType type, size_t length, const std::string& value, size_t valuePos, size_t valueLength); void createTokenCurrentString(TokenType type, size_t length); bool convertInteger(size_t start, size_t end, int64_t& result); bool convertFloat(size_t start, size_t end, double& result); bool parseOperator(); TextFile* input; std::string currentLine; size_t lineNumber; size_t linePos; Token token; bool equActive; }; class TokenStreamTokenizer: public Tokenizer { public: void init(const std::vector& tokens) { clearTokens(); for (const Token &tok: tokens) addToken(tok); resetPosition(); } }; #pragma region "File: Core/ExpressionFunctionHandler.h" #include #include #include #include #include #include class ExpressionFunctionHandle; class ExpressionInternal; class Identifier; class Label; struct ExpressionValue; struct Token; using ExpressionFunction = ExpressionValue (*)(const Identifier& funcName, const std::vector&); using ExpressionLabelFunction = ExpressionValue (*)(const Identifier& funcName, const std::vector> &); enum class ExpFuncSafety { // Result may depend entirely on the internal state Unsafe, // Result is unsafe in conditional blocks, safe otherwise ConditionalUnsafe, // Result is completely independent of the internal state Safe, }; class ExpressionFunctionHandler { friend class ExpressionFunctionHandle; public: static ExpressionFunctionHandler &instance(); std::optional find(const Identifier &name) const; void reset(); void updateArchitecture(); bool addFunction(const Identifier &name, ExpressionFunction functor, size_t minParams, size_t maxParams, ExpFuncSafety safety); bool addLabelFunction(const Identifier &name, ExpressionLabelFunction functor, size_t minParams, size_t maxParams, ExpFuncSafety safety); bool addUserFunction(const Identifier &name, const std::vector ¶meters, const std::vector &content); private: struct Entry { std::function> &)> f; size_t minParams = 0; size_t maxParams = 0; ExpFuncSafety safety = ExpFuncSafety::Unsafe; }; ExpressionFunctionHandler(); bool registerEntry(const Identifier &name, Entry entry); std::map entries; std::vector architectureFunctions; bool registeringArchitecture = false; }; class ExpressionFunctionHandle { public: ExpressionFunctionHandle(const ExpressionFunctionHandler::Entry &entry); size_t minParams() const; size_t maxParams() const; ExpFuncSafety safety() const; ExpressionValue execute(const std::vector> ¶meters) const; private: const ExpressionFunctionHandler::Entry &impl; }; #pragma region "File: Core/ExpressionFunctions.h" #include #include #include #include bool getExpFuncParameter(const std::vector& parameters, size_t index, int64_t& dest, const Identifier &funcName, bool optional); bool getExpFuncParameter(const std::vector& parameters, size_t index, const StringLiteral*& dest, const Identifier &funcName, bool optional); struct ExpressionFunctionEntry { const char *name; ExpressionFunction function; size_t minParams; size_t maxParams; ExpFuncSafety safety; }; struct ExpressionLabelFunctionEntry { const char *name; ExpressionLabelFunction function; size_t minParams; size_t maxParams; ExpFuncSafety safety; }; void registerExpressionFunctions(ExpressionFunctionHandler &handler); #pragma region "File: Core/SymbolData.h" #include #include #include #include class AssemblerFile; struct SymDataSymbol { std::string name; int64_t address; bool operator<(const SymDataSymbol& other) const { return address < other.address; } }; struct SymDataAddressInfo { int64_t address; size_t fileIndex; size_t lineNumber; bool operator<(const SymDataAddressInfo& other) const { return address < other.address; } }; struct SymDataFunction { int64_t address; size_t size; bool operator<(const SymDataFunction& other) const { return address < other.address; } }; struct SymDataData { int64_t address; size_t size; int type; bool operator<(const SymDataData& other) const { if (address != other.address) return address < other.address; if (size != other.size) return size < other.size; return type < other.type; } }; struct SymDataModule { AssemblerFile* file; std::vector symbols; std::vector functions; std::set data; }; struct SymDataModuleInfo { unsigned int crc32; }; class SymbolData { public: enum DataType { Data8, Data16, Data32, Data64, DataAscii }; SymbolData(); void clear(); void setNocashSymFileName(const fs::path& name, int version) { nocashSymFileName = name; nocashSymVersion = version; }; void write(); void setEnabled(bool b) { enabled = b; }; void addLabel(int64_t address, const std::string& name); void addData(int64_t address, size_t size, DataType type); void startModule(AssemblerFile* file); void endModule(AssemblerFile* file); void startFunction(int64_t address); void endFunction(int64_t address); private: void writeNocashSym(); size_t addFileName(const std::string& fileName); fs::path nocashSymFileName; bool enabled; int nocashSymVersion; // entry 0 is for data without parent modules std::vector modules; std::vector files; int currentModule; int currentFunction; }; #pragma region "File: Util/Util.h" #include #include #include std::string convertUnicodeCharToUtf8(char32_t character); std::string convertWStringToUtf8(std::wstring_view source); bool stringToInt(const std::string& line, size_t start, size_t end, int64_t& result); int32_t getFloatBits(float value); float bitsToFloat(int32_t value); int64_t getDoubleBits(double value); std::string toLowercase(const std::string& str); size_t replaceAll(std::string& str, const char* oldValue,const std::string& newValue); bool startsWith(const std::string& str, const char* value, size_t stringPos = 0); #pragma region "File: Util/FileClasses.h" #include #include #include class TextFile { public: enum Encoding { ASCII, UTF8, UTF16LE, UTF16BE, SJIS, GUESS }; enum Mode { Read, Write }; TextFile(); ~TextFile(); void openMemory(const std::string& content); bool open(const fs::path& fileName, Mode mode, Encoding defaultEncoding = GUESS); bool open(Mode mode, Encoding defaultEncoding = GUESS); bool isOpen() { return fromMemory || stream.is_open(); }; bool atEnd() { return isOpen() && mode == Read && tell() >= size_; }; long size() { return size_; }; void close(); bool hasGuessedEncoding() { return guessedEncoding; }; bool isFromMemory() { return fromMemory; } int getNumLines() { return lineCount; } void setFileName(const fs::path& name) { fileName = name; }; const fs::path& getFileName() { return fileName; }; std::string readLine(); std::vector readAll(); void write(const char* value); void write(const std::string& value); void writeLine(const char* line); void writeLine(const std::string& line); void writeLines(std::vector& list); template void writeFormat(const char* text, const Args&... args) { std::string message = tfm::format(text,args...); write(message); } bool hasError() { return errorText.size() != 0 && !errorRetrieved; }; const std::string& getErrorText() { errorRetrieved = true; return errorText; }; private: char32_t readCharacter(); std::string readLineUtf8(); std::string readLineSJIS(); long tell(); void seek(long pos); fs::fstream stream; fs::path fileName; Encoding encoding; Mode mode; bool recursion; bool guessedEncoding; long size_; std::string errorText; bool errorRetrieved; bool fromMemory; std::string content; size_t contentPos; int lineCount; std::string buf; size_t bufPos; inline unsigned char bufGetChar() { if (fromMemory) return content[contentPos++]; if (buf.size() <= bufPos) { bufFillRead(); if (buf.size() == 0) return 0; } ++contentPos; return buf[bufPos++]; } inline unsigned short bufGet16LE() { unsigned char c1 = bufGetChar(); unsigned char c2 = bufGetChar(); return c1 | (c2 << 8); } inline unsigned short bufGet16BE() { unsigned char c1 = bufGetChar(); unsigned char c2 = bufGetChar(); return c2 | (c1 << 8); } void bufPut(const void *p, const size_t len); void bufPut(const char c); void bufFillRead(); void bufDrainWrite(); }; std::optional sjisToUnicode(unsigned short); TextFile::Encoding getEncodingFromString(const std::string& str); #pragma region "File: Util/ByteArray.h" #include #include #if defined(_MSC_VER) && !defined(ssize_t) typedef intptr_t ssize_t; #endif typedef unsigned char byte; enum class Endianness { Big, Little }; class ByteArray { public: ByteArray(); ByteArray(const ByteArray& other); ByteArray(byte* data, size_t size); ByteArray(ByteArray&& other); ~ByteArray(); ByteArray& operator=(ByteArray& other); ByteArray& operator=(ByteArray&& other); size_t append(const ByteArray& other); size_t append(void* data, size_t size); size_t appendByte(byte b) { return append(&b,1); }; void replaceByte(size_t pos, byte b) { data_[pos] = b; }; void replaceBytes(size_t pos, byte* data, size_t size); void reserveBytes(size_t count, byte value = 0); void alignSize(size_t alignment); int getWord(size_t pos, Endianness endianness = Endianness::Little) const { if (pos+1 >= this->size()) return -1; unsigned char* d = (unsigned char*) this->data(); if (endianness == Endianness::Little) { return d[pos+0] | (d[pos+1] << 8); } else { return d[pos+1] | (d[pos+0] << 8); } } int getDoubleWord(size_t pos, Endianness endianness = Endianness::Little) const { if (pos+3 >= this->size()) return -1; unsigned char* d = (unsigned char*) this->data(); if (endianness == Endianness::Little) { return d[pos+0] | (d[pos+1] << 8) | (d[pos+2] << 16) | (d[pos+3] << 24); } else { return d[pos+3] | (d[pos+2] << 8) | (d[pos+1] << 16) | (d[pos+0] << 24); } } void replaceWord(size_t pos, unsigned int w, Endianness endianness = Endianness::Little) { if (pos+1 >= this->size()) return; unsigned char* d = (unsigned char*) this->data(); if (endianness == Endianness::Little) { d[pos+0] = w & 0xFF; d[pos+1] = (w >> 8) & 0xFF; } else { d[pos+0] = (w >> 8) & 0xFF; d[pos+1] = w & 0xFF; } } void replaceDoubleWord(size_t pos, unsigned int w, Endianness endianness = Endianness::Little) { if (pos+3 >= this->size()) return; unsigned char* d = (unsigned char*) this->data(); if (endianness == Endianness::Little) { d[pos+0] = w & 0xFF; d[pos+1] = (w >> 8) & 0xFF; d[pos+2] = (w >> 16) & 0xFF; d[pos+3] = (w >> 24) & 0xFF; } else { d[pos+0] = (w >> 24) & 0xFF; d[pos+1] = (w >> 16) & 0xFF; d[pos+2] = (w >> 8) & 0xFF; d[pos+3] = w & 0xFF; } } byte& operator [](size_t index) { return data_[index]; }; const byte& operator [](size_t index) const { return data_[index]; }; size_t size() const { return size_; }; byte* data(size_t pos = 0) const { return &data_[pos]; }; void clear() { size_ = 0; }; void resize(size_t newSize); ByteArray mid(size_t start, ssize_t length = 0); ByteArray left(size_t length) { return mid(0,length); }; ByteArray right(size_t length) { return mid(size_-length,length); }; static ByteArray fromFile(const fs::path& fileName, long start = 0, size_t size = 0); bool toFile(const fs::path& fileName); private: void grow(size_t neededSize); byte* data_; size_t size_; size_t allocatedSize_; }; #pragma region "File: Core/FileManager.h" #include #include class SymbolData; struct SymDataModuleInfo; class AssemblerFile { public: virtual ~AssemblerFile() { }; virtual bool open(bool onlyCheck) = 0; virtual void close() = 0; virtual bool isOpen() = 0; virtual bool write(void* data, size_t length) = 0; virtual int64_t getVirtualAddress() = 0; virtual int64_t getPhysicalAddress() = 0; virtual int64_t getHeaderSize() = 0; virtual bool seekVirtual(int64_t virtualAddress) = 0; virtual bool seekPhysical(int64_t physicalAddress) = 0; virtual bool getModuleInfo(SymDataModuleInfo& info) { return false; }; virtual bool hasFixedVirtualAddress() { return false; }; virtual void beginSymData(SymbolData& symData) { }; virtual void endSymData(SymbolData& symData) { }; virtual const fs::path& getFileName() = 0; }; class GenericAssemblerFile: public AssemblerFile { public: GenericAssemblerFile(const fs::path& fileName, int64_t headerSize, bool overwrite); GenericAssemblerFile(const fs::path& fileName, const fs::path& originalFileName, int64_t headerSize); virtual bool open(bool onlyCheck); virtual void close() { if (stream.is_open()) stream.close(); }; virtual bool isOpen() { return stream.is_open(); }; virtual bool write(void* data, size_t length); virtual int64_t getVirtualAddress() { return virtualAddress; }; virtual int64_t getPhysicalAddress() { return virtualAddress-headerSize; }; virtual int64_t getHeaderSize() { return headerSize; }; virtual bool seekVirtual(int64_t virtualAddress); virtual bool seekPhysical(int64_t physicalAddress); virtual bool hasFixedVirtualAddress() { return true; }; virtual const fs::path& getFileName() { return fileName; }; const fs::path& getOriginalFileName() { return originalName; }; int64_t getOriginalHeaderSize() { return originalHeaderSize; }; void setHeaderSize(int64_t size) { headerSize = size; }; private: enum Mode { Open, Create, Copy }; Mode mode; int64_t originalHeaderSize; int64_t headerSize; int64_t virtualAddress; fs::ofstream stream; fs::path fileName; fs::path originalName; }; class FileManager { public: FileManager(); ~FileManager(); void reset(); bool openFile(std::shared_ptr file, bool onlyCheck); void addFile(std::shared_ptr file); bool hasOpenFile() { return activeFile != nullptr; }; void closeFile(); bool write(void* data, size_t length); bool writeU8(uint8_t data); bool writeU16(uint16_t data); bool writeU32(uint32_t data); bool writeU64(uint64_t data); int64_t getVirtualAddress(); int64_t getPhysicalAddress(); int64_t getHeaderSize(); bool seekVirtual(int64_t virtualAddress); bool seekPhysical(int64_t physicalAddress); bool advanceMemory(size_t bytes); std::shared_ptr getOpenFile() { return activeFile; }; int64_t getOpenFileID(); void setEndianness(Endianness endianness) { this->endianness = endianness; }; Endianness getEndianness() { return endianness; } private: bool checkActiveFile(); std::vector> files; std::shared_ptr activeFile; Endianness endianness; Endianness ownEndianness; }; #pragma region "File: Core/ELF/ElfTypes.h" /////////////////////// // ELF Header Constants // File type enum ElfType { ET_NONE =0, ET_REL =1, ET_EXEC =2, ET_DYN =3, ET_CORE =4, ET_LOPROC =0xFF00, ET_HIPROC =0xFFFF, }; // Machine/Architecture enum ElfMachine { EM_NONE =0, EM_MIPS =8, EM_ARM =40, EM_SH2 =42 }; // File version #define EV_NONE 0 #define EV_CURRENT 1 // Identification index #define EI_MAG0 0 #define EI_MAG1 1 #define EI_MAG2 2 #define EI_MAG3 3 #define EI_CLASS 4 #define EI_DATA 5 #define EI_VERSION 6 #define EI_PAD 7 #define EI_NIDENT 16 // Magic number #define ELFMAG0 0x7F #define ELFMAG1 'E' #define ELFMAG2 'L' #define ELFMAG3 'F' // File class #define ELFCLASSNONE 0 #define ELFCLASS32 1 #define ELFCLASS64 2 // Encoding #define ELFDATANONE 0 #define ELFDATA2LSB 1 #define ELFDATA2MSB 2 ///////////////////// // Sections constants // Section indexes #define SHN_UNDEF 0 #define SHN_LORESERVE 0xFF00 #define SHN_LOPROC 0xFF00 #define SHN_HIPROC 0xFF1F #define SHN_ABS 0xFFF1 #define SHN_COMMON 0xFFF2 #define SHN_HIRESERVE 0xFFFF // Section types #define SHT_NULL 0 #define SHT_PROGBITS 1 #define SHT_SYMTAB 2 #define SHT_STRTAB 3 #define SHT_RELA 4 #define SHT_HASH 5 #define SHT_DYNAMIC 6 #define SHT_NOTE 7 #define SHT_NOBITS 8 #define SHT_REL 9 #define SHT_SHLIB 10 #define SHT_DYNSYM 11 #define SHT_INIT_ARRAY 14 #define SHT_LOPROC 0x70000000 #define SHT_HIPROC 0x7FFFFFFF #define SHT_LOUSER 0x80000000 #define SHT_HIUSER 0xFFFFFFFF // Custom section types #define SHT_PSPREL 0x700000a0 // Section flags enum ElfSectionFlags { SHF_WRITE =0x1, SHF_ALLOC =0x2, SHF_EXECINSTR =0x4, SHF_MASKPROC =0xF0000000, }; // Symbol binding #define STB_LOCAL 0 #define STB_GLOBAL 1 #define STB_WEAK 2 #define STB_LOPROC 13 #define STB_HIPROC 15 // Symbol types #define STT_NOTYPE 0 #define STT_OBJECT 1 #define STT_FUNC 2 #define STT_SECTION 3 #define STT_FILE 4 #define STT_LOPROC 13 #define STT_HIPROC 15 // Undefined name #define STN_UNDEF 0 // Relocation types #define R_386_NONE 0 #define R_386_32 1 #define R_386_PC32 2 #define R_386_GOT32 3 #define R_386_PLT32 4 #define R_386_COPY 5 #define R_386_GLOB_DAT 6 #define R_386_JMP_SLOT 7 #define R_386_RELATIVE 8 #define R_386_GOTOFF 9 #define R_386_GOTPC 10 // Segment types #define PT_NULL 0 #define PT_LOAD 1 #define PT_DYNAMIC 2 #define PT_INTERP 3 #define PT_NOTE 4 #define PT_SHLIB 5 #define PT_PHDR 6 #define PT_LOPROC 0x70000000 #define PT_HIPROC 0x7FFFFFFF // Segment flags #define PF_X 1 #define PF_W 2 #define PF_R 4 // Dynamic Array Tags #define DT_NULL 0 #define DT_NEEDED 1 #define DT_PLTRELSZ 2 #define DT_PLTGOT 3 #define DT_HASH 4 #define DT_STRTAB 5 #define DT_SYMTAB 6 #define DT_RELA 7 #define DT_RELASZ 8 #define DT_RELAENT 9 #define DT_STRSZ 10 #define DT_SYMENT 11 #define DT_INIT 12 #define DT_FINI 13 #define DT_SONAME 14 #define DT_RPATH 15 #define DT_SYMBOLIC 16 #define DT_REL 17 #define DT_RELSZ 18 #define DT_RELENT 19 #define DT_PLTREL 20 #define DT_DEBUG 21 #define DT_TEXTREL 22 #define DT_JMPREL 23 #define DT_LOPROC 0x70000000 #define DT_HIPROC 0x7FFFFFFF typedef unsigned int Elf32_Addr; typedef unsigned short Elf32_Half; typedef unsigned int Elf32_Off; typedef signed int Elf32_Sword; typedef unsigned int Elf32_Word; // ELF file header struct Elf32_Ehdr { unsigned char e_ident[EI_NIDENT]; Elf32_Half e_type; Elf32_Half e_machine; Elf32_Word e_version; Elf32_Addr e_entry; Elf32_Off e_phoff; Elf32_Off e_shoff; Elf32_Word e_flags; Elf32_Half e_ehsize; Elf32_Half e_phentsize; Elf32_Half e_phnum; Elf32_Half e_shentsize; Elf32_Half e_shnum; Elf32_Half e_shstrndx; }; // Section header struct Elf32_Shdr { Elf32_Word sh_name; Elf32_Word sh_type; Elf32_Word sh_flags; Elf32_Addr sh_addr; Elf32_Off sh_offset; Elf32_Word sh_size; Elf32_Word sh_link; Elf32_Word sh_info; Elf32_Word sh_addralign; Elf32_Word sh_entsize; }; // Segment header struct Elf32_Phdr { Elf32_Word p_type; Elf32_Off p_offset; Elf32_Addr p_vaddr; Elf32_Addr p_paddr; Elf32_Word p_filesz; Elf32_Word p_memsz; Elf32_Word p_flags; Elf32_Word p_align; }; // Symbol table entry struct Elf32_Sym { Elf32_Word st_name; Elf32_Addr st_value; Elf32_Word st_size; unsigned char st_info; unsigned char st_other; Elf32_Half st_shndx; }; #define ELF32_ST_BIND(i) ((i)>>4) #define ELF32_ST_TYPE(i) ((i)&0xf) #define ELF32_ST_INFO(b,t) (((b)<<4)+((t)&0xf)) // Relocation entries struct Elf32_Rel { Elf32_Addr r_offset; Elf32_Word r_info; unsigned char getType() { return r_info & 0xFF; } Elf32_Word getSymbolNum() { return r_info >> 8; } }; struct Elf32_Rela { Elf32_Addr r_offset; Elf32_Word r_info; Elf32_Sword r_addend; unsigned char getType() { return r_info & 0xFF; } Elf32_Word getSymbolNum() { return r_info >> 8; } }; #define ELF32_R_SYM(i) ((i)>>8) #define ELF32_R_TYPE(i) ((unsigned char)(i)) #define ELF32_R_INFO(s,t) (((s)<<8 )+(unsigned char)(t)) #pragma region "File: Core/ELF/ElfFile.h" #include enum ElfPart { ELFPART_SEGMENTTABLE, ELFPART_SECTIONTABLE, ELFPART_SEGMENTS, ELFPART_SEGMENTLESSSECTIONS }; class ElfSegment; class ElfSection; class ElfFile { public: bool load(const fs::path&fileName, bool sort); bool load(ByteArray& data, bool sort); void save(const fs::path& fileName); Elf32_Half getType() { return fileHeader.e_type; }; Elf32_Half getMachine() { return fileHeader.e_machine; }; Endianness getEndianness() { return fileHeader.e_ident[EI_DATA] == ELFDATA2MSB ? Endianness::Big : Endianness::Little; } size_t getSegmentCount() { return segments.size(); }; ElfSegment* getSegment(size_t index) { return segments[index]; }; int findSegmentlessSection(const std::string& name); ElfSection* getSegmentlessSection(size_t index) { return segmentlessSections[index]; }; size_t getSegmentlessSectionCount() { return segmentlessSections.size(); }; ByteArray& getFileData() { return fileData; } int getSymbolCount(); bool getSymbol(Elf32_Sym& symbol, size_t index); const char* getStrTableString(size_t pos); private: void loadElfHeader(); void writeHeader(ByteArray& data, size_t pos, Endianness endianness); void loadProgramHeader(Elf32_Phdr& header, ByteArray& data, size_t pos); void loadSectionHeader(Elf32_Shdr& header, ByteArray& data, size_t pos); void loadSectionNames(); void determinePartOrder(); Elf32_Ehdr fileHeader; std::vector segments; std::vector sections; std::vector segmentlessSections; ByteArray fileData; ElfPart partsOrder[4]; ElfSection* symTab; ElfSection* strTab; }; class ElfSection { public: ElfSection(Elf32_Shdr header); void setName(std::string& name) { this->name = name; }; const std::string& getName() { return name; }; void setData(ByteArray& data) { this->data = data; }; void setOwner(ElfSegment* segment); bool hasOwner() { return owner != nullptr; }; void writeHeader(ByteArray& data, size_t pos, Endianness endianness); void writeData(ByteArray& output); void setOffsetBase(int base); ByteArray& getData() { return data; }; Elf32_Word getType() { return header.sh_type; }; Elf32_Off getOffset() { return header.sh_offset; }; Elf32_Word getSize() { return header.sh_size; }; Elf32_Word getNameOffset() { return header.sh_name; }; Elf32_Word getAlignment() { return header.sh_addralign; }; Elf32_Addr getAddress() { return header.sh_addr; }; Elf32_Half getInfo() { return header.sh_info; }; Elf32_Word getFlags() { return header.sh_flags; }; private: Elf32_Shdr header; std::string name; ByteArray data; ElfSegment* owner; }; class ElfSegment { public: ElfSegment(Elf32_Phdr header, ByteArray& segmentData); bool isSectionPartOf(ElfSection* section); void addSection(ElfSection* section); Elf32_Off getOffset() { return header.p_offset; }; Elf32_Word getPhysSize() { return header.p_filesz; }; Elf32_Word getType() { return header.p_type; }; Elf32_Addr getVirtualAddress() { return header.p_vaddr; }; size_t getSectionCount() { return sections.size(); }; void writeHeader(ByteArray& data, size_t pos, Endianness endianness); void writeData(ByteArray& output); void splitSections(); int findSection(const std::string& name); ElfSection* getSection(size_t index) { return sections[index]; }; void writeToData(size_t offset, void* data, size_t size); void sortSections(); private: Elf32_Phdr header; ByteArray data; std::vector sections; ElfSection* paddrSection; }; struct RelocationData { int64_t opcodeOffset; int64_t relocationBase; uint32_t opcode; int32_t addend; int64_t symbolAddress; int targetSymbolType; int targetSymbolInfo; }; #pragma region "File: Core/ELF/ElfRelocator.h" #include struct ElfRelocatorCtor { Identifier symbolName; size_t size; }; struct RelocationAction { RelocationAction(int64_t offset, uint32_t newValue) : offset(offset), newValue(newValue) {} int64_t offset; uint32_t newValue; }; class CAssemblerCommand; class Identifier; class Parser; class IElfRelocator { public: virtual ~IElfRelocator() {}; virtual int expectedMachine() const = 0; virtual bool isDummyRelocationType(int type) const { return false; } virtual bool relocateOpcode(int type, const RelocationData& data, std::vector& actions, std::vector& errors) = 0; virtual bool finish(std::vector& actions, std::vector& errors) { return true; } virtual void setSymbolAddress(RelocationData& data, int64_t symbolAddress, int symbolType) = 0; virtual std::unique_ptr generateCtorStub(std::vector& ctors); }; class Label; class SymbolData; struct ElfRelocatorSection { ElfSection* section; size_t index; ElfSection* relSection; std::shared_ptr