// armips assembler v0.11 // https://github.com/Kingcom/armips/ // To simplify compilation, all files have been concatenated into one. // MIPS only, ARM is 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. */ // file: stdafx.h #define _CRT_SECURE_NO_WARNINGS #undef __STRICT_ANSI__ #if defined(__clang__) #if __has_feature(cxx_exceptions) #define ARMIPS_EXCEPTIONS 1 #else #define ARMIPS_EXCEPTIONS 0 #endif #elif defined(_MSC_VER) && defined(_CPPUNWIND) #define ARMIPS_EXCEPTIONS 1 #elif defined(__EXCEPTIONS) || defined(__cpp_exceptions) #define ARMIPS_EXCEPTIONS 1 #else #define ARMIPS_EXCEPTIONS 0 #endif #include #include #include #include #include #include #include #include #include #include #include #define formatString tfm::format // Custom make_unique so that C++14 support will not be necessary for compilation template std::unique_ptr make_unique(Args&&... args) { return std::unique_ptr(new T(std::forward(args)...)); } // 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::wostream // * 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::wcout: // // std::wstring weekday = L"Wednesday"; // const wchar_t* month = L"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::wstring 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, L"%s, %s %d, %.2d:%.2d\n", // weekday, month, day, hour, min); // // The other returns a std::wstring: // // std::wstring date = tfm::format(L"%s, %s %d, %.2d:%.2d\n", // weekday, month, day, hour, min); // std::wcout << 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::wcout, L"%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 #define TINYFORMAT_ALLOW_WCHAR_STRINGS #define TINYFORMAT_USE_VARIADIC_TEMPLATES #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 { wchar_t dummy[2]; }; struct succeed { wchar_t 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::wostream& /*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::wostream& out, const T& value) { out << static_cast(value); } }; #ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND template::value> struct formatZeroIntegerWorkaround { static bool invoke(std::wostream& /**/, const T& /**/) { return false; } }; template struct formatZeroIntegerWorkaround { static bool invoke(std::wostream& 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 wchar_tacters to the given stream. template inline void formatTruncated(std::wostream& out, const T& value, int ntrunc) { std::wostringstream tmp; tmp << value; std::wstring 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::wostream& out, type* value, int ntrunc) \ { \ std::streamsize len = 0; \ while(len < ntrunc && value[len] != 0) \ ++len; \ out.write(value, len); \ } // Overload for const wchar_t* and wchar_t*. Could overload for signed & unsigned // wchar_t too, but these are technically unneeded for printf compatibility. TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(const wchar_t) TINYFORMAT_DEFINE_FORMAT_TRUNCATED_CSTR(wchar_t) #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::wostream& out, const wchar_t* /*fmtBegin*/, const wchar_t* 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 wchar_t 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 wchar_t*). 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 wchar_tacters may be read. detail::formatTruncated(out, value, ntrunc); } else out << value; } // Overloaded version for wchar_t types to support printing as an integer #define TINYFORMAT_DEFINE_FORMATVALUE_CHAR(wchar_tType) \ inline void formatValue(std::wostream& out, const wchar_t* /*fmtBegin*/, \ const wchar_t* fmtEnd, int /**/, wchar_tType 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::wostream& out, const wchar_t* fmtBegin, const wchar_t* 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::wostream& out, const wchar_t* fmtBegin, const wchar_t* 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::wostream& out, const wchar_t* fmtBegin, const wchar_t* 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 wchar_t*& 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 wchar_t* printFormatStringLiteral(std::wostream& out, const wchar_t* fmt) { const wchar_t* 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 wchar_tacter after the end of the current format spec. inline const wchar_t* streamStateFromFormat(std::wostream& out, bool& spacePadPositive, int& ntrunc, const wchar_t* 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 wchar_t* 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); // Falls through case 'x': case 'p': out.setf(std::ios::hex, std::ios::basefield); intConversion = true; break; case 'E': out.setf(std::ios::uppercase); // 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); // Falls through case 'f': out.setf(std::ios::fixed, std::ios::floatfield); break; case 'G': out.setf(std::ios::uppercase); // 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::wostream& out, const wchar_t* 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(); wchar_t 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 wchar_t* 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::wostringstream tmpStream; tmpStream.copyfmt(out); tmpStream.setf(std::ios::showpos); arg.format(tmpStream, fmt, fmtEnd, ntrunc); std::wstring 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::wostream& out, const wchar_t* 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::wostream& out, const wchar_t* 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::wostream& out, const wchar_t* 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::wstring format(const wchar_t* fmt, const Args&... args) { std::wostringstream oss; format(oss, fmt, args...); return oss.str(); } /// Format list of arguments to std::wcout, according to the given format string template void printf(const wchar_t* fmt, const Args&... args) { format(std::wcout, fmt, args...); } template void printfln(const wchar_t* fmt, const Args&... args) { format(std::wcout, fmt, args...); std::wcout << '\n'; } #else // C++98 version inline void format(std::wostream& out, const wchar_t* fmt) { vformat(out, fmt, makeFormatList()); } inline std::wstring format(const wchar_t* fmt) { std::wostringstream oss; format(oss, fmt); return oss.str(); } inline void printf(const wchar_t* fmt) { format(std::wcout, fmt); } inline void printfln(const wchar_t* fmt) { format(std::wcout, fmt); std::wcout << '\n'; } #define TINYFORMAT_MAKE_FORMAT_FUNCS(n) \ \ template \ void format(std::wostream& out, const wchar_t* fmt, TINYFORMAT_VARARGS(n)) \ { \ vformat(out, fmt, makeFormatList(TINYFORMAT_PASSARGS(n))); \ } \ \ template \ std::wstring format(const wchar_t* fmt, TINYFORMAT_VARARGS(n)) \ { \ std::wostringstream oss; \ format(oss, fmt, TINYFORMAT_PASSARGS(n)); \ return oss.str(); \ } \ \ template \ void printf(const wchar_t* fmt, TINYFORMAT_VARARGS(n)) \ { \ format(std::wcout, fmt, TINYFORMAT_PASSARGS(n)); \ } \ \ template \ void printfln(const wchar_t* fmt, TINYFORMAT_VARARGS(n)) \ { \ format(std::wcout, fmt, TINYFORMAT_PASSARGS(n)); \ std::wcout << '\n'; \ } TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_FUNCS) #undef TINYFORMAT_MAKE_FORMAT_FUNCS #endif } // namespace tinyformat #endif // TINYFORMAT_H_INCLUDED // file: Commands/CAssemblerCommand.h class TempData; class SymbolData; class CAssemblerCommand { public: CAssemblerCommand(); virtual ~CAssemblerCommand() { }; virtual bool Validate() = 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: virtual bool Validate() { return false; }; virtual void Encode() const { }; virtual void writeTempData(TempData& tempData) const { }; virtual void writeSymData(SymbolData& symData) const { }; }; class InvalidCommand: public CAssemblerCommand { public: virtual bool Validate() { return false; }; virtual void Encode() const { }; virtual void writeTempData(TempData& tempData) const { }; virtual void writeSymData(SymbolData& symData) const { }; }; // file: Core/Expression.h #include inline std::wstring to_wstring(int64_t value) { return formatString(L"%d", value); } inline std::wstring to_wstring(double value) { return formatString(L"%#.17g", value); } 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; } ExpressionValue(int64_t value) { type = ExpressionValueType::Integer; intValue = value; } ExpressionValue(double value) { type = ExpressionValueType::Float; floatValue = value; } ExpressionValue(const std::wstring& value) { type = ExpressionValueType::String; strValue = value; } 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; } struct { int64_t intValue; double floatValue; }; std::wstring 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 Label; struct ExpressionFunctionEntry; struct ExpressionLabelFunctionEntry; class ExpressionInternal { public: ExpressionInternal(); ~ExpressionInternal(); ExpressionInternal(int64_t value); ExpressionInternal(double value); ExpressionInternal(const std::wstring& value, OperatorType type); ExpressionInternal(OperatorType op, ExpressionInternal* a = nullptr, ExpressionInternal* b = nullptr, ExpressionInternal* c = nullptr); ExpressionInternal(const std::wstring& name, const std::vector& parameters); ExpressionValue evaluate(); std::wstring toString(); bool isIdentifier() { return type == OperatorType::Identifier; } std::wstring getStringValue() { return strValue; } void replaceMemoryPos(const std::wstring& identifierName); bool simplify(bool inUnknownOrFalseBlock); unsigned int getFileNum() { return fileNum; } unsigned int getSection() { return section; } private: void allocate(size_t count); void deallocate(); std::wstring formatFunctionCall(); ExpressionValue executeExpressionFunctionCall(const ExpressionFunctionEntry& entry); ExpressionValue executeExpressionLabelFunctionCall(const ExpressionLabelFunctionEntry& entry); ExpressionValue executeFunctionCall(); bool checkParameterCount(size_t min, size_t max); OperatorType type; ExpressionInternal** children; size_t childrenCount; union { int64_t intValue; double floatValue; }; std::wstring strValue; unsigned int fileNum, section; }; class Expression { public: Expression(); ExpressionValue evaluate(); bool isLoaded() const { return expression != nullptr; } void setExpression(ExpressionInternal* exp, bool inUnknownOrFalseBlock); void replaceMemoryPos(const std::wstring& 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(std::wstring& dest, bool convert) { if (expression == nullptr) return false; ExpressionValue value = expression->evaluate(); if (convert && value.isInt()) { dest = to_wstring(value.intValue); return true; } if (convert && value.isFloat()) { dest = to_wstring(value.floatValue); return true; } if (value.isString() == false) return false; dest = value.strValue; return true; } bool evaluateIdentifier(std::wstring& dest) { if (expression == nullptr || expression->isIdentifier() == false) return false; dest = expression->getStringValue(); return true; } std::wstring toString() { return expression != nullptr ? expression->toString() : L""; }; private: std::shared_ptr expression; std::wstring originalText; bool constExpression; }; Expression createConstExpression(int64_t value); // file: Core/ExpressionFunctions.h #include bool getExpFuncParameter(const std::vector& parameters, size_t index, int64_t& dest, const std::wstring& funcName, bool optional); bool getExpFuncParameter(const std::vector& parameters, size_t index, const std::wstring*& dest, const std::wstring& funcName, bool optional); using ExpressionFunction = ExpressionValue (*)(const std::wstring& funcName, const std::vector&); using ExpressionLabelFunction = ExpressionValue (*)(const std::wstring& 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, }; struct ExpressionFunctionEntry { ExpressionFunction function; size_t minParams; size_t maxParams; ExpFuncSafety safety; }; struct ExpressionLabelFunctionEntry { ExpressionLabelFunction function; size_t minParams; size_t maxParams; ExpFuncSafety safety; }; using ExpressionFunctionMap = std::map; using ExpressionLabelFunctionMap = std::map; extern const ExpressionFunctionMap expressionFunctions; extern const ExpressionLabelFunctionMap expressionLabelFunctions; // file: Core/SymbolData.h #include class AssemblerFile; struct SymDataSymbol { std::wstring 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 std::wstring& name, int version) { nocashSymFileName = name; nocashSymVersion = version; }; void write(); void setEnabled(bool b) { enabled = b; }; void addLabel(int64_t address, const std::wstring& 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::wstring& fileName); std::wstring nocashSymFileName; bool enabled; int nocashSymVersion; // entry 0 is for data without parent modules std::vector modules; std::vector files; int currentModule; int currentFunction; }; // file: Util/Util.h #include #include typedef std::vector StringList; std::wstring convertUtf8ToWString(const char* source); std::string convertWCharToUtf8(wchar_t character); ;std::string convertWStringToUtf8(const std::wstring& source); std::wstring intToHexString(unsigned int value, int digits, bool prefix = false); std::wstring intToString(unsigned int value, int digits); bool stringToInt(const std::wstring& 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); StringList getStringListFromArray(wchar_t** source, int count); StringList splitString(const std::wstring& str, const wchar_t delim, bool skipEmpty); int64_t fileSize(const std::wstring& fileName); bool fileExists(const std::wstring& strFilename); bool copyFile(const std::wstring& existingFile, const std::wstring& newFile); bool deleteFile(const std::wstring& fileName);; std::wstring toWLowercase(const std::string& str); std::wstring getFileNameFromPath(const std::wstring& path); size_t replaceAll(std::wstring& str, const wchar_t* oldValue,const std::wstring& newValue); bool startsWith(const std::wstring& str, const wchar_t* value, size_t stringPos = 0); enum class OpenFileMode { ReadBinary, WriteBinary, ReadWriteBinary }; FILE* openFile(const std::wstring& fileName, OpenFileMode mode); std::wstring getCurrentDirectory(); bool changeDirectory(const std::wstring& dir); bool isAbsolutePath(const std::wstring& path); #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0])) #endif // file: Util/FileClasses.h #include class BinaryFile { public: enum Mode { Read, Write, ReadWrite }; BinaryFile(); ~BinaryFile(); bool open(const std::wstring& fileName, Mode mode); bool open(Mode mode); bool isOpen() { return handle != nullptr; }; bool atEnd() { return isOpen() && mode != Write && ftell(handle) == size_; }; void setPos(long pos) { if (isOpen()) fseek(handle,pos,SEEK_SET); }; long pos() { return isOpen() ? ftell(handle) : -1; } long size() { return size_; }; void close(); void setFileName(const std::wstring& name) { fileName = name; }; const std::wstring& getFileName() { return fileName; }; size_t read(void* dest, size_t length); size_t write(void* source, size_t length); private: FILE* handle; std::wstring fileName; Mode mode; long size_; }; class TextFile { public: enum Encoding { ASCII, UTF8, UTF16LE, UTF16BE, SJIS, GUESS }; enum Mode { Read, Write }; TextFile(); ~TextFile(); void openMemory(const std::wstring& content); bool open(const std::wstring& fileName, Mode mode, Encoding defaultEncoding = GUESS); bool open(Mode mode, Encoding defaultEncoding = GUESS); bool isOpen() { return fromMemory || handle != nullptr; }; 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 std::wstring& name) { fileName = name; }; const std::wstring& getFileName() { return fileName; }; wchar_t readCharacter(); std::wstring readLine(); StringList readAll(); void writeCharacter(wchar_t character); void write(const wchar_t* line); void write(const std::wstring& line); void write(const char* value); void write(const std::string& value); void writeLine(const wchar_t* line); void writeLine(const std::wstring& line); void writeLine(const char* line); void writeLine(const std::string& line); void writeLines(StringList& list); template void writeFormat(const wchar_t* text, const Args&... args) { std::wstring message = formatString(text,args...); write(message); } bool hasError() { return errorText.size() != 0 && !errorRetrieved; }; const std::wstring& getErrorText() { errorRetrieved = true; return errorText; }; private: long tell(); void seek(long pos); FILE* handle; std::wstring fileName; Encoding encoding; Mode mode; bool recursion; bool guessedEncoding; long size_; std::wstring errorText; bool errorRetrieved; bool fromMemory; std::wstring content; size_t contentPos; int lineCount; std::string buf; size_t bufPos; inline unsigned char bufGetChar() { if (buf.size() <= bufPos) { bufFillRead(); if (buf.size() == 0) return 0; } return buf[bufPos++]; } inline unsigned short bufGet16LE() { char c1 = bufGetChar(); char c2 = bufGetChar(); return c1 | (c2 << 8); } inline unsigned short bufGet16BE() { char c1 = bufGetChar(); 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(); }; wchar_t sjisToUnicode(unsigned short); TextFile::Encoding getEncodingFromString(const std::wstring& str); // file: Util/ByteArray.h #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 std::wstring& fileName, long start = 0, size_t size = 0); bool toFile(const std::wstring& fileName); private: void grow(size_t neededSize); byte* data_; size_t size_; size_t allocatedSize_; }; // file: Core/FileManager.h #include 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 std::wstring& getFileName() = 0; }; class GenericAssemblerFile: public AssemblerFile { public: GenericAssemblerFile(const std::wstring& fileName, int64_t headerSize, bool overwrite); GenericAssemblerFile(const std::wstring& fileName, const std::wstring& originalFileName, int64_t headerSize); virtual bool open(bool onlyCheck); virtual void close() { if (handle.isOpen()) handle.close(); }; virtual bool isOpen() { return handle.isOpen(); }; 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 std::wstring& getFileName() { return fileName; }; const std::wstring& 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; BinaryFile handle; std::wstring fileName; std::wstring 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; }; 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; }; // 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, }; // 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; }; #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)) // 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 std::wstring&fileName, bool sort); bool load(ByteArray& data, bool sort); void save(const std::wstring&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, int pos, Endianness endianness); void loadProgramHeader(Elf32_Phdr& header, ByteArray& data, int pos); void loadSectionHeader(Elf32_Shdr& header, ByteArray& data, int 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, int 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, int 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; int64_t symbolAddress; int targetSymbolType; int targetSymbolInfo; }; // file: Core/ELF/ElfRelocator.h struct ElfRelocatorCtor { std::wstring 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 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) { return nullptr; } }; class Label; struct ElfRelocatorSection { ElfSection* section; size_t index; ElfSection* relSection; std::shared_ptr