[
  {
    "path": ".github/workflows/gh-pages.yml",
    "content": "on: \n  push:\n    branches: [master]\n    \njobs:\n  gh-pages:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v3\n      - name: install doxygen\n        run: |\n          sudo apt-get update\n          sudo apt-get install -y doxygen\n      - name: genereate docs\n        run: |\n          doxygen\n          sed -i -e 's/:smiley:/\\&#x1f603;/g' -e 's/:skull:/\\&#x1f480;/g' html/index.html\n      - name: push docs\n        run: |\n          git fetch --depth=1 origin gh-pages\n          git checkout gh-pages\n          rm -rf docs\n          mv html docs\n          git config --local user.email \"docs-action@github.com\"\n          git config --local user.name \"GitHub Action (docs)\"\n          git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}\n          git diff --quiet || (git add docs && git commit -m 'Add docs' && git push origin gh-pages && echo Add docs)\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: tests\non:\n  push:\n  pull_request:\n\njobs:\n  tests_on_ubuntu_x86_64:\n    name: Tests on Ubuntu (x86_64 and i686)\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v3\n      with:\n        submodules: true\n    - name: Install packages\n      run: |\n        sudo dpkg --add-architecture i386\n        sudo apt-get update\n        sudo apt-get install -y gcc-multilib gcc-mingw-w64-x86-64 gcc-mingw-w64-i686 libgcc-s1:i386 libstdc++6:i386 wine32 wine64 wine-binfmt\n        sudo apt-get remove mono-runtime\n        echo WINEPATH=$(ls -d /usr/lib/gcc/*-mingw*/*-win32 | tr '\\n' ';') >> $GITHUB_ENV\n    - name: build\n      run: |\n        cd tests && make cross\n    - name: x86_64 -> x86_64\n      run: |\n        cd tests && ./test-prog-x86_64 x86_64\n    - name: x86_64 -> i386\n      run: |\n        cd tests && ./test-prog-x86_64 i386\n    - name: i386 -> i386\n      run: |\n        cd tests && ./test-prog-i386 i386\n    - name: x86_64 -> x86_64 (cloned thread)\n      run: |\n        cd tests && ./test-prog-x86_64 x86_64 --cloned-thread\n    - name: mingw-x64 mingw-x64\n      run: |\n        cd tests && ./test-prog-mingw-x64.exe mingw-x64\n    - name: mingw-32 mingw-32\n      run: |\n        cd tests && ./test-prog-mingw-32.exe mingw-32\n\n  tests_on_mac:\n    name: Tests on MacOS (x86_64)\n    runs-on: macos-latest\n    steps:\n    - uses: actions/checkout@v3\n      with:\n        submodules: true\n    - name: run tests\n      run: |\n        sudo make check\n\n  tests_on_windows:\n    name: Tests on Windows (x64 and x86)\n    runs-on: windows-latest\n    steps:\n    - uses: actions/checkout@v3\n      with:\n        submodules: true\n    - uses: ilammy/msvc-dev-cmd@v1\n      with:\n        arch: x64\n    - name: x64 -> x64 tests on Windows\n      shell: cmd\n      run: |\n        nmake -nologo -f Makefile.win32 check\n        if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL%\n        copy tests\\test-prog.exe tests\\test-prog-x64.exe \n        nmake -nologo -f Makefile.win32 clean\n    - uses: ilammy/msvc-dev-cmd@v1\n      with:\n        arch: x86\n    - name: x86 -> x86 tests on Windows\n      shell: cmd\n      run: |\n        nmake -nologo -f Makefile.win32 check\n    - name: x64 -> x86 tests on Windows\n      shell: cmd\n      run: |\n        cd tests && .\\test-prog-x64.exe\n    - name: mingw32-w64 (x86_64)\n      shell: bash\n      run: |\n        CC=x86_64-w64-mingw32-gcc make clean check\n\n  tests_on_alpine_x86_64:\n    name: Tests on Alpine (x86_64 only)\n    runs-on: ubuntu-latest\n    container: alpine\n    steps:\n    - name: Install packages\n      run: |\n        apk add gcc musl-dev git make\n    - uses: actions/checkout@v3\n      with:\n        submodules: true\n    - name: run tests\n      run: |\n        make check\n"
  },
  {
    "path": ".gitignore",
    "content": "*~\n*.a\n*.dll\n*.exe\n*.exp\n*.lib\n*.o\n*.obj\n*.so\n*.dylib\n/cmd/injector\n/tests/test-prog\n/tests/test-prog-*\n/tests/test-target\n/tests/test-target-*\n"
  },
  {
    "path": "Doxyfile",
    "content": "# Doxyfile 1.9.1\n\n# This file describes the settings to be used by the documentation system\n# doxygen (www.doxygen.org) for a project.\n#\n# All text after a double hash (##) is considered a comment and is placed in\n# front of the TAG it is preceding.\n#\n# All text after a single hash (#) is considered a comment and will be ignored.\n# The format is:\n# TAG = value [value, ...]\n# For lists, items can also be appended using:\n# TAG += value [value, ...]\n# Values that contain spaces should be placed between quotes (\\\" \\\").\n\n#---------------------------------------------------------------------------\n# Project related configuration options\n#---------------------------------------------------------------------------\n\n# This tag specifies the encoding used for all characters in the configuration\n# file that follow. The default is UTF-8 which is also the encoding used for all\n# text before the first occurrence of this tag. Doxygen uses libiconv (or the\n# iconv built into libc) for the transcoding. See\n# https://www.gnu.org/software/libiconv/ for the list of possible encodings.\n# The default value is: UTF-8.\n\nDOXYFILE_ENCODING      = UTF-8\n\n# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by\n# double-quotes, unless you are using Doxywizard) that should identify the\n# project for which the documentation is generated. This name is used in the\n# title of most generated pages and in a few other places.\n# The default value is: My Project.\n\nPROJECT_NAME           = \"Injector\"\n\n# The PROJECT_NUMBER tag can be used to enter a project or revision number. This\n# could be handy for archiving the generated documentation or if some version\n# control system is used.\n\nPROJECT_NUMBER         =\n\n# Using the PROJECT_BRIEF tag one can provide an optional one line description\n# for a project that appears at the top of each page and should give viewer a\n# quick idea about the purpose of the project. Keep the description short.\n\nPROJECT_BRIEF          =\n\n# With the PROJECT_LOGO tag one can specify a logo or an icon that is included\n# in the documentation. The maximum height of the logo should not exceed 55\n# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy\n# the logo to the output directory.\n\nPROJECT_LOGO           =\n\n# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path\n# into which the generated documentation will be written. If a relative path is\n# entered, it will be relative to the location where doxygen was started. If\n# left blank the current directory will be used.\n\nOUTPUT_DIRECTORY       =\n\n# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-\n# directories (in 2 levels) under the output directory of each output format and\n# will distribute the generated files over these directories. Enabling this\n# option can be useful when feeding doxygen a huge amount of source files, where\n# putting all generated files in the same directory would otherwise causes\n# performance problems for the file system.\n# The default value is: NO.\n\nCREATE_SUBDIRS         = NO\n\n# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII\n# characters to appear in the names of generated files. If set to NO, non-ASCII\n# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode\n# U+3044.\n# The default value is: NO.\n\nALLOW_UNICODE_NAMES    = NO\n\n# The OUTPUT_LANGUAGE tag is used to specify the language in which all\n# documentation generated by doxygen is written. Doxygen will use this\n# information to generate all constant output in the proper language.\n# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,\n# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),\n# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,\n# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),\n# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,\n# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,\n# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,\n# Ukrainian and Vietnamese.\n# The default value is: English.\n\nOUTPUT_LANGUAGE        = English\n\n# The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all\n# documentation generated by doxygen is written. Doxygen will use this\n# information to generate all generated output in the proper direction.\n# Possible values are: None, LTR, RTL and Context.\n# The default value is: None.\n\nOUTPUT_TEXT_DIRECTION  = None\n\n# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member\n# descriptions after the members that are listed in the file and class\n# documentation (similar to Javadoc). Set to NO to disable this.\n# The default value is: YES.\n\nBRIEF_MEMBER_DESC      = YES\n\n# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief\n# description of a member or function before the detailed description\n#\n# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the\n# brief descriptions will be completely suppressed.\n# The default value is: YES.\n\nREPEAT_BRIEF           = YES\n\n# This tag implements a quasi-intelligent brief description abbreviator that is\n# used to form the text in various listings. Each string in this list, if found\n# as the leading text of the brief description, will be stripped from the text\n# and the result, after processing the whole list, is used as the annotated\n# text. Otherwise, the brief description is used as-is. If left blank, the\n# following values are used ($name is automatically replaced with the name of\n# the entity):The $name class, The $name widget, The $name file, is, provides,\n# specifies, contains, represents, a, an and the.\n\nABBREVIATE_BRIEF       = \"The $name class\" \\\n                         \"The $name widget\" \\\n                         \"The $name file\" \\\n                         is \\\n                         provides \\\n                         specifies \\\n                         contains \\\n                         represents \\\n                         a \\\n                         an \\\n                         the\n\n# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then\n# doxygen will generate a detailed section even if there is only a brief\n# description.\n# The default value is: NO.\n\nALWAYS_DETAILED_SEC    = NO\n\n# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all\n# inherited members of a class in the documentation of that class as if those\n# members were ordinary class members. Constructors, destructors and assignment\n# operators of the base classes will not be shown.\n# The default value is: NO.\n\nINLINE_INHERITED_MEMB  = NO\n\n# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path\n# before files name in the file list and in the header files. If set to NO the\n# shortest path that makes the file name unique will be used\n# The default value is: YES.\n\nFULL_PATH_NAMES        = YES\n\n# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.\n# Stripping is only done if one of the specified strings matches the left-hand\n# part of the path. The tag can be used to show relative paths in the file list.\n# If left blank the directory from which doxygen is run is used as the path to\n# strip.\n#\n# Note that you can specify absolute paths here, but also relative paths, which\n# will be relative from the directory where doxygen is started.\n# This tag requires that the tag FULL_PATH_NAMES is set to YES.\n\nSTRIP_FROM_PATH        =\n\n# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the\n# path mentioned in the documentation of a class, which tells the reader which\n# header file to include in order to use a class. If left blank only the name of\n# the header file containing the class definition is used. Otherwise one should\n# specify the list of include paths that are normally passed to the compiler\n# using the -I flag.\n\nSTRIP_FROM_INC_PATH    =\n\n# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but\n# less readable) file names. This can be useful is your file systems doesn't\n# support long names like on DOS, Mac, or CD-ROM.\n# The default value is: NO.\n\nSHORT_NAMES            = NO\n\n# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the\n# first line (until the first dot) of a Javadoc-style comment as the brief\n# description. If set to NO, the Javadoc-style will behave just like regular Qt-\n# style comments (thus requiring an explicit @brief command for a brief\n# description.)\n# The default value is: NO.\n\nJAVADOC_AUTOBRIEF      = NO\n\n# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line\n# such as\n# /***************\n# as being the beginning of a Javadoc-style comment \"banner\". If set to NO, the\n# Javadoc-style will behave just like regular comments and it will not be\n# interpreted by doxygen.\n# The default value is: NO.\n\nJAVADOC_BANNER         = NO\n\n# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first\n# line (until the first dot) of a Qt-style comment as the brief description. If\n# set to NO, the Qt-style will behave just like regular Qt-style comments (thus\n# requiring an explicit \\brief command for a brief description.)\n# The default value is: NO.\n\nQT_AUTOBRIEF           = NO\n\n# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a\n# multi-line C++ special comment block (i.e. a block of //! or /// comments) as\n# a brief description. This used to be the default behavior. The new default is\n# to treat a multi-line C++ comment block as a detailed description. Set this\n# tag to YES if you prefer the old behavior instead.\n#\n# Note that setting this tag to YES also means that rational rose comments are\n# not recognized any more.\n# The default value is: NO.\n\nMULTILINE_CPP_IS_BRIEF = NO\n\n# By default Python docstrings are displayed as preformatted text and doxygen's\n# special commands cannot be used. By setting PYTHON_DOCSTRING to NO the\n# doxygen's special commands can be used and the contents of the docstring\n# documentation blocks is shown as doxygen documentation.\n# The default value is: YES.\n\nPYTHON_DOCSTRING       = YES\n\n# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the\n# documentation from any documented member that it re-implements.\n# The default value is: YES.\n\nINHERIT_DOCS           = YES\n\n# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new\n# page for each member. If set to NO, the documentation of a member will be part\n# of the file/class/namespace that contains it.\n# The default value is: NO.\n\nSEPARATE_MEMBER_PAGES  = NO\n\n# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen\n# uses this value to replace tabs by spaces in code fragments.\n# Minimum value: 1, maximum value: 16, default value: 4.\n\nTAB_SIZE               = 4\n\n# This tag can be used to specify a number of aliases that act as commands in\n# the documentation. An alias has the form:\n# name=value\n# For example adding\n# \"sideeffect=@par Side Effects:\\n\"\n# will allow you to put the command \\sideeffect (or @sideeffect) in the\n# documentation, which will result in a user-defined paragraph with heading\n# \"Side Effects:\". You can put \\n's in the value part of an alias to insert\n# newlines (in the resulting output). You can put ^^ in the value part of an\n# alias to insert a newline as if a physical newline was in the original file.\n# When you need a literal { or } or , in the value part of an alias you have to\n# escape them by means of a backslash (\\), this can lead to conflicts with the\n# commands \\{ and \\} for these it is advised to use the version @{ and @} or use\n# a double escape (\\\\{ and \\\\})\n\nALIASES                =\n\n# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources\n# only. Doxygen will then generate output that is more tailored for C. For\n# instance, some of the names that are used will be different. The list of all\n# members will be omitted, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_FOR_C  = YES\n\n# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or\n# Python sources only. Doxygen will then generate output that is more tailored\n# for that language. For instance, namespaces will be presented as packages,\n# qualified scopes will look different, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_JAVA   = NO\n\n# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran\n# sources. Doxygen will then generate output that is tailored for Fortran.\n# The default value is: NO.\n\nOPTIMIZE_FOR_FORTRAN   = NO\n\n# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL\n# sources. Doxygen will then generate output that is tailored for VHDL.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_VHDL   = NO\n\n# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice\n# sources only. Doxygen will then generate output that is more tailored for that\n# language. For instance, namespaces will be presented as modules, types will be\n# separated into more groups, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_SLICE  = NO\n\n# Doxygen selects the parser to use depending on the extension of the files it\n# parses. With this tag you can assign which parser to use for a given\n# extension. Doxygen has a built-in mapping, but you can override or extend it\n# using this tag. The format is ext=language, where ext is a file extension, and\n# language is one of the parsers supported by doxygen: IDL, Java, JavaScript,\n# Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice, VHDL,\n# Fortran (fixed format Fortran: FortranFixed, free formatted Fortran:\n# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser\n# tries to guess whether the code is fixed or free formatted code, this is the\n# default for Fortran type files). For instance to make doxygen treat .inc files\n# as Fortran files (default is PHP), and .f files as C (default is Fortran),\n# use: inc=Fortran f=C.\n#\n# Note: For files without extension you can use no_extension as a placeholder.\n#\n# Note that for custom extensions you also need to set FILE_PATTERNS otherwise\n# the files are not read by doxygen. When specifying no_extension you should add\n# * to the FILE_PATTERNS.\n#\n# Note see also the list of default file extension mappings.\n\nEXTENSION_MAPPING      =\n\n# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments\n# according to the Markdown format, which allows for more readable\n# documentation. See https://daringfireball.net/projects/markdown/ for details.\n# The output of markdown processing is further processed by doxygen, so you can\n# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in\n# case of backward compatibilities issues.\n# The default value is: YES.\n\nMARKDOWN_SUPPORT       = YES\n\n# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up\n# to that level are automatically included in the table of contents, even if\n# they do not have an id attribute.\n# Note: This feature currently applies only to Markdown headings.\n# Minimum value: 0, maximum value: 99, default value: 5.\n# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.\n\nTOC_INCLUDE_HEADINGS   = 5\n\n# When enabled doxygen tries to link words that correspond to documented\n# classes, or namespaces to their corresponding documentation. Such a link can\n# be prevented in individual cases by putting a % sign in front of the word or\n# globally by setting AUTOLINK_SUPPORT to NO.\n# The default value is: YES.\n\nAUTOLINK_SUPPORT       = YES\n\n# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want\n# to include (a tag file for) the STL sources as input, then you should set this\n# tag to YES in order to let doxygen match functions declarations and\n# definitions whose arguments contain STL classes (e.g. func(std::string);\n# versus func(std::string) {}). This also make the inheritance and collaboration\n# diagrams that involve STL classes more complete and accurate.\n# The default value is: NO.\n\nBUILTIN_STL_SUPPORT    = NO\n\n# If you use Microsoft's C++/CLI language, you should set this option to YES to\n# enable parsing support.\n# The default value is: NO.\n\nCPP_CLI_SUPPORT        = NO\n\n# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:\n# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen\n# will parse them like normal C++ but will assume all classes use public instead\n# of private inheritance when no explicit protection keyword is present.\n# The default value is: NO.\n\nSIP_SUPPORT            = NO\n\n# For Microsoft's IDL there are propget and propput attributes to indicate\n# getter and setter methods for a property. Setting this option to YES will make\n# doxygen to replace the get and set methods by a property in the documentation.\n# This will only work if the methods are indeed getting or setting a simple\n# type. If this is not the case, or you want to show the methods anyway, you\n# should set this option to NO.\n# The default value is: YES.\n\nIDL_PROPERTY_SUPPORT   = YES\n\n# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC\n# tag is set to YES then doxygen will reuse the documentation of the first\n# member in the group (if any) for the other members of the group. By default\n# all members of a group must be documented explicitly.\n# The default value is: NO.\n\nDISTRIBUTE_GROUP_DOC   = NO\n\n# If one adds a struct or class to a group and this option is enabled, then also\n# any nested class or struct is added to the same group. By default this option\n# is disabled and one has to add nested compounds explicitly via \\ingroup.\n# The default value is: NO.\n\nGROUP_NESTED_COMPOUNDS = NO\n\n# Set the SUBGROUPING tag to YES to allow class member groups of the same type\n# (for instance a group of public functions) to be put as a subgroup of that\n# type (e.g. under the Public Functions section). Set it to NO to prevent\n# subgrouping. Alternatively, this can be done per class using the\n# \\nosubgrouping command.\n# The default value is: YES.\n\nSUBGROUPING            = YES\n\n# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions\n# are shown inside the group in which they are included (e.g. using \\ingroup)\n# instead of on a separate page (for HTML and Man pages) or section (for LaTeX\n# and RTF).\n#\n# Note that this feature does not work in combination with\n# SEPARATE_MEMBER_PAGES.\n# The default value is: NO.\n\nINLINE_GROUPED_CLASSES = NO\n\n# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions\n# with only public data fields or simple typedef fields will be shown inline in\n# the documentation of the scope in which they are defined (i.e. file,\n# namespace, or group documentation), provided this scope is documented. If set\n# to NO, structs, classes, and unions are shown on a separate page (for HTML and\n# Man pages) or section (for LaTeX and RTF).\n# The default value is: NO.\n\nINLINE_SIMPLE_STRUCTS  = NO\n\n# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or\n# enum is documented as struct, union, or enum with the name of the typedef. So\n# typedef struct TypeS {} TypeT, will appear in the documentation as a struct\n# with name TypeT. When disabled the typedef will appear as a member of a file,\n# namespace, or class. And the struct will be named TypeS. This can typically be\n# useful for C code in case the coding convention dictates that all compound\n# types are typedef'ed and only the typedef is referenced, never the tag name.\n# The default value is: NO.\n\nTYPEDEF_HIDES_STRUCT   = NO\n\n# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This\n# cache is used to resolve symbols given their name and scope. Since this can be\n# an expensive process and often the same symbol appears multiple times in the\n# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small\n# doxygen will become slower. If the cache is too large, memory is wasted. The\n# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range\n# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536\n# symbols. At the end of a run doxygen will report the cache usage and suggest\n# the optimal cache size from a speed point of view.\n# Minimum value: 0, maximum value: 9, default value: 0.\n\nLOOKUP_CACHE_SIZE      = 0\n\n# The NUM_PROC_THREADS specifies the number threads doxygen is allowed to use\n# during processing. When set to 0 doxygen will based this on the number of\n# cores available in the system. You can set it explicitly to a value larger\n# than 0 to get more control over the balance between CPU load and processing\n# speed. At this moment only the input processing can be done using multiple\n# threads. Since this is still an experimental feature the default is set to 1,\n# which efficively disables parallel processing. Please report any issues you\n# encounter. Generating dot graphs in parallel is controlled by the\n# DOT_NUM_THREADS setting.\n# Minimum value: 0, maximum value: 32, default value: 1.\n\nNUM_PROC_THREADS       = 1\n\n#---------------------------------------------------------------------------\n# Build related configuration options\n#---------------------------------------------------------------------------\n\n# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in\n# documentation are documented, even if no documentation was available. Private\n# class members and static file members will be hidden unless the\n# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.\n# Note: This will also disable the warnings about undocumented members that are\n# normally produced when WARNINGS is set to YES.\n# The default value is: NO.\n\nEXTRACT_ALL            = NO\n\n# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will\n# be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PRIVATE        = NO\n\n# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual\n# methods of a class will be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PRIV_VIRTUAL   = NO\n\n# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal\n# scope will be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PACKAGE        = NO\n\n# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be\n# included in the documentation.\n# The default value is: NO.\n\nEXTRACT_STATIC         = NO\n\n# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined\n# locally in source files will be included in the documentation. If set to NO,\n# only classes defined in header files are included. Does not have any effect\n# for Java sources.\n# The default value is: YES.\n\nEXTRACT_LOCAL_CLASSES  = YES\n\n# This flag is only useful for Objective-C code. If set to YES, local methods,\n# which are defined in the implementation section but not in the interface are\n# included in the documentation. If set to NO, only methods in the interface are\n# included.\n# The default value is: NO.\n\nEXTRACT_LOCAL_METHODS  = NO\n\n# If this flag is set to YES, the members of anonymous namespaces will be\n# extracted and appear in the documentation as a namespace called\n# 'anonymous_namespace{file}', where file will be replaced with the base name of\n# the file that contains the anonymous namespace. By default anonymous namespace\n# are hidden.\n# The default value is: NO.\n\nEXTRACT_ANON_NSPACES   = NO\n\n# If this flag is set to YES, the name of an unnamed parameter in a declaration\n# will be determined by the corresponding definition. By default unnamed\n# parameters remain unnamed in the output.\n# The default value is: YES.\n\nRESOLVE_UNNAMED_PARAMS = YES\n\n# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all\n# undocumented members inside documented classes or files. If set to NO these\n# members will be included in the various overviews, but no documentation\n# section is generated. This option has no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_MEMBERS     = NO\n\n# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all\n# undocumented classes that are normally visible in the class hierarchy. If set\n# to NO, these classes will be included in the various overviews. This option\n# has no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_CLASSES     = NO\n\n# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend\n# declarations. If set to NO, these declarations will be included in the\n# documentation.\n# The default value is: NO.\n\nHIDE_FRIEND_COMPOUNDS  = NO\n\n# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any\n# documentation blocks found inside the body of a function. If set to NO, these\n# blocks will be appended to the function's detailed documentation block.\n# The default value is: NO.\n\nHIDE_IN_BODY_DOCS      = NO\n\n# The INTERNAL_DOCS tag determines if documentation that is typed after a\n# \\internal command is included. If the tag is set to NO then the documentation\n# will be excluded. Set it to YES to include the internal documentation.\n# The default value is: NO.\n\nINTERNAL_DOCS          = NO\n\n# With the correct setting of option CASE_SENSE_NAMES doxygen will better be\n# able to match the capabilities of the underlying filesystem. In case the\n# filesystem is case sensitive (i.e. it supports files in the same directory\n# whose names only differ in casing), the option must be set to YES to properly\n# deal with such files in case they appear in the input. For filesystems that\n# are not case sensitive the option should be be set to NO to properly deal with\n# output files written for symbols that only differ in casing, such as for two\n# classes, one named CLASS and the other named Class, and to also support\n# references to files without having to specify the exact matching casing. On\n# Windows (including Cygwin) and MacOS, users should typically set this option\n# to NO, whereas on Linux or other Unix flavors it should typically be set to\n# YES.\n# The default value is: system dependent.\n\nCASE_SENSE_NAMES       = YES\n\n# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with\n# their full class and namespace scopes in the documentation. If set to YES, the\n# scope will be hidden.\n# The default value is: NO.\n\nHIDE_SCOPE_NAMES       = NO\n\n# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will\n# append additional text to a page's title, such as Class Reference. If set to\n# YES the compound reference will be hidden.\n# The default value is: NO.\n\nHIDE_COMPOUND_REFERENCE= NO\n\n# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of\n# the files that are included by a file in the documentation of that file.\n# The default value is: YES.\n\nSHOW_INCLUDE_FILES     = YES\n\n# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each\n# grouped member an include statement to the documentation, telling the reader\n# which file to include in order to use the member.\n# The default value is: NO.\n\nSHOW_GROUPED_MEMB_INC  = NO\n\n# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include\n# files with double quotes in the documentation rather than with sharp brackets.\n# The default value is: NO.\n\nFORCE_LOCAL_INCLUDES   = NO\n\n# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the\n# documentation for inline members.\n# The default value is: YES.\n\nINLINE_INFO            = YES\n\n# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the\n# (detailed) documentation of file and class members alphabetically by member\n# name. If set to NO, the members will appear in declaration order.\n# The default value is: YES.\n\nSORT_MEMBER_DOCS       = YES\n\n# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief\n# descriptions of file, namespace and class members alphabetically by member\n# name. If set to NO, the members will appear in declaration order. Note that\n# this will also influence the order of the classes in the class list.\n# The default value is: NO.\n\nSORT_BRIEF_DOCS        = NO\n\n# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the\n# (brief and detailed) documentation of class members so that constructors and\n# destructors are listed first. If set to NO the constructors will appear in the\n# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.\n# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief\n# member documentation.\n# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting\n# detailed member documentation.\n# The default value is: NO.\n\nSORT_MEMBERS_CTORS_1ST = NO\n\n# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy\n# of group names into alphabetical order. If set to NO the group names will\n# appear in their defined order.\n# The default value is: NO.\n\nSORT_GROUP_NAMES       = NO\n\n# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by\n# fully-qualified names, including namespaces. If set to NO, the class list will\n# be sorted only by class name, not including the namespace part.\n# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.\n# Note: This option applies only to the class list, not to the alphabetical\n# list.\n# The default value is: NO.\n\nSORT_BY_SCOPE_NAME     = NO\n\n# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper\n# type resolution of all parameters of a function it will reject a match between\n# the prototype and the implementation of a member function even if there is\n# only one candidate or it is obvious which candidate to choose by doing a\n# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still\n# accept a match between prototype and implementation in such cases.\n# The default value is: NO.\n\nSTRICT_PROTO_MATCHING  = NO\n\n# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo\n# list. This list is created by putting \\todo commands in the documentation.\n# The default value is: YES.\n\nGENERATE_TODOLIST      = YES\n\n# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test\n# list. This list is created by putting \\test commands in the documentation.\n# The default value is: YES.\n\nGENERATE_TESTLIST      = YES\n\n# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug\n# list. This list is created by putting \\bug commands in the documentation.\n# The default value is: YES.\n\nGENERATE_BUGLIST       = YES\n\n# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)\n# the deprecated list. This list is created by putting \\deprecated commands in\n# the documentation.\n# The default value is: YES.\n\nGENERATE_DEPRECATEDLIST= YES\n\n# The ENABLED_SECTIONS tag can be used to enable conditional documentation\n# sections, marked by \\if <section_label> ... \\endif and \\cond <section_label>\n# ... \\endcond blocks.\n\nENABLED_SECTIONS       =\n\n# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the\n# initial value of a variable or macro / define can have for it to appear in the\n# documentation. If the initializer consists of more lines than specified here\n# it will be hidden. Use a value of 0 to hide initializers completely. The\n# appearance of the value of individual variables and macros / defines can be\n# controlled using \\showinitializer or \\hideinitializer command in the\n# documentation regardless of this setting.\n# Minimum value: 0, maximum value: 10000, default value: 30.\n\nMAX_INITIALIZER_LINES  = 30\n\n# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at\n# the bottom of the documentation of classes and structs. If set to YES, the\n# list will mention the files that were used to generate the documentation.\n# The default value is: YES.\n\nSHOW_USED_FILES        = YES\n\n# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This\n# will remove the Files entry from the Quick Index and from the Folder Tree View\n# (if specified).\n# The default value is: YES.\n\nSHOW_FILES             = YES\n\n# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces\n# page. This will remove the Namespaces entry from the Quick Index and from the\n# Folder Tree View (if specified).\n# The default value is: YES.\n\nSHOW_NAMESPACES        = YES\n\n# The FILE_VERSION_FILTER tag can be used to specify a program or script that\n# doxygen should invoke to get the current version for each file (typically from\n# the version control system). Doxygen will invoke the program by executing (via\n# popen()) the command command input-file, where command is the value of the\n# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided\n# by doxygen. Whatever the program writes to standard output is used as the file\n# version. For an example see the documentation.\n\nFILE_VERSION_FILTER    =\n\n# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed\n# by doxygen. The layout file controls the global structure of the generated\n# output files in an output format independent way. To create the layout file\n# that represents doxygen's defaults, run doxygen with the -l option. You can\n# optionally specify a file name after the option, if omitted DoxygenLayout.xml\n# will be used as the name of the layout file.\n#\n# Note that if you run doxygen from a directory containing a file called\n# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE\n# tag is left empty.\n\nLAYOUT_FILE            =\n\n# The CITE_BIB_FILES tag can be used to specify one or more bib files containing\n# the reference definitions. This must be a list of .bib files. The .bib\n# extension is automatically appended if omitted. This requires the bibtex tool\n# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.\n# For LaTeX the style of the bibliography can be controlled using\n# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the\n# search path. See also \\cite for info how to create references.\n\nCITE_BIB_FILES         =\n\n#---------------------------------------------------------------------------\n# Configuration options related to warning and progress messages\n#---------------------------------------------------------------------------\n\n# The QUIET tag can be used to turn on/off the messages that are generated to\n# standard output by doxygen. If QUIET is set to YES this implies that the\n# messages are off.\n# The default value is: NO.\n\nQUIET                  = NO\n\n# The WARNINGS tag can be used to turn on/off the warning messages that are\n# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES\n# this implies that the warnings are on.\n#\n# Tip: Turn warnings on while writing the documentation.\n# The default value is: YES.\n\nWARNINGS               = YES\n\n# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate\n# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag\n# will automatically be disabled.\n# The default value is: YES.\n\nWARN_IF_UNDOCUMENTED   = YES\n\n# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for\n# potential errors in the documentation, such as not documenting some parameters\n# in a documented function, or documenting parameters that don't exist or using\n# markup commands wrongly.\n# The default value is: YES.\n\nWARN_IF_DOC_ERROR      = YES\n\n# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that\n# are documented, but have no documentation for their parameters or return\n# value. If set to NO, doxygen will only warn about wrong or incomplete\n# parameter documentation, but not about the absence of documentation. If\n# EXTRACT_ALL is set to YES then this flag will automatically be disabled.\n# The default value is: NO.\n\nWARN_NO_PARAMDOC       = NO\n\n# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when\n# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS\n# then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but\n# at the end of the doxygen process doxygen will return with a non-zero status.\n# Possible values are: NO, YES and FAIL_ON_WARNINGS.\n# The default value is: NO.\n\nWARN_AS_ERROR          = NO\n\n# The WARN_FORMAT tag determines the format of the warning messages that doxygen\n# can produce. The string should contain the $file, $line, and $text tags, which\n# will be replaced by the file and line number from which the warning originated\n# and the warning text. Optionally the format may contain $version, which will\n# be replaced by the version of the file (if it could be obtained via\n# FILE_VERSION_FILTER)\n# The default value is: $file:$line: $text.\n\nWARN_FORMAT            = \"$file:$line: $text\"\n\n# The WARN_LOGFILE tag can be used to specify a file to which warning and error\n# messages should be written. If left blank the output is written to standard\n# error (stderr).\n\nWARN_LOGFILE           =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the input files\n#---------------------------------------------------------------------------\n\n# The INPUT tag is used to specify the files and/or directories that contain\n# documented source files. You may enter file names like myfile.cpp or\n# directories like /usr/src/myproject. Separate the files or directories with\n# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING\n# Note: If this tag is empty the current directory is searched.\n\nINPUT                  = README.md include\n\n# This tag can be used to specify the character encoding of the source files\n# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses\n# libiconv (or the iconv built into libc) for the transcoding. See the libiconv\n# documentation (see:\n# https://www.gnu.org/software/libiconv/) for the list of possible encodings.\n# The default value is: UTF-8.\n\nINPUT_ENCODING         = UTF-8\n\n# If the value of the INPUT tag contains directories, you can use the\n# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and\n# *.h) to filter out the source-files in the directories.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# read by doxygen.\n#\n# Note the list of default checked file patterns might differ from the list of\n# default file extension mappings.\n#\n# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,\n# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,\n# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,\n# *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C comment),\n# *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd, *.vhdl,\n# *.ucf, *.qsf and *.ice.\n\nFILE_PATTERNS          = *.c \\\n                         *.cc \\\n                         *.cxx \\\n                         *.cpp \\\n                         *.c++ \\\n                         *.java \\\n                         *.ii \\\n                         *.ixx \\\n                         *.ipp \\\n                         *.i++ \\\n                         *.inl \\\n                         *.idl \\\n                         *.ddl \\\n                         *.odl \\\n                         *.h \\\n                         *.hh \\\n                         *.hxx \\\n                         *.hpp \\\n                         *.h++ \\\n                         *.cs \\\n                         *.d \\\n                         *.php \\\n                         *.php4 \\\n                         *.php5 \\\n                         *.phtml \\\n                         *.inc \\\n                         *.m \\\n                         *.markdown \\\n                         *.md \\\n                         *.mm \\\n                         *.dox \\\n                         *.py \\\n                         *.pyw \\\n                         *.f90 \\\n                         *.f95 \\\n                         *.f03 \\\n                         *.f08 \\\n                         *.f18 \\\n                         *.f \\\n                         *.for \\\n                         *.vhd \\\n                         *.vhdl \\\n                         *.ucf \\\n                         *.qsf \\\n                         *.ice\n\n# The RECURSIVE tag can be used to specify whether or not subdirectories should\n# be searched for input files as well.\n# The default value is: NO.\n\nRECURSIVE              = NO\n\n# The EXCLUDE tag can be used to specify files and/or directories that should be\n# excluded from the INPUT source files. This way you can easily exclude a\n# subdirectory from a directory tree whose root is specified with the INPUT tag.\n#\n# Note that relative paths are relative to the directory from which doxygen is\n# run.\n\nEXCLUDE                =\n\n# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or\n# directories that are symbolic links (a Unix file system feature) are excluded\n# from the input.\n# The default value is: NO.\n\nEXCLUDE_SYMLINKS       = NO\n\n# If the value of the INPUT tag contains directories, you can use the\n# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude\n# certain files from those directories.\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories for example use the pattern */test/*\n\nEXCLUDE_PATTERNS       =\n\n# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names\n# (namespaces, classes, functions, etc.) that should be excluded from the\n# output. The symbol name can be a fully qualified name, a word, or if the\n# wildcard * is used, a substring. Examples: ANamespace, AClass,\n# AClass::ANamespace, ANamespace::*Test\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories use the pattern */test/*\n\nEXCLUDE_SYMBOLS        =\n\n# The EXAMPLE_PATH tag can be used to specify one or more files or directories\n# that contain example code fragments that are included (see the \\include\n# command).\n\nEXAMPLE_PATH           =\n\n# If the value of the EXAMPLE_PATH tag contains directories, you can use the\n# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and\n# *.h) to filter out the source-files in the directories. If left blank all\n# files are included.\n\nEXAMPLE_PATTERNS       = *\n\n# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be\n# searched for input files to be used with the \\include or \\dontinclude commands\n# irrespective of the value of the RECURSIVE tag.\n# The default value is: NO.\n\nEXAMPLE_RECURSIVE      = NO\n\n# The IMAGE_PATH tag can be used to specify one or more files or directories\n# that contain images that are to be included in the documentation (see the\n# \\image command).\n\nIMAGE_PATH             =\n\n# The INPUT_FILTER tag can be used to specify a program that doxygen should\n# invoke to filter for each input file. Doxygen will invoke the filter program\n# by executing (via popen()) the command:\n#\n# <filter> <input-file>\n#\n# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the\n# name of an input file. Doxygen will then use the output that the filter\n# program writes to standard output. If FILTER_PATTERNS is specified, this tag\n# will be ignored.\n#\n# Note that the filter must not add or remove lines; it is applied before the\n# code is scanned, but not when the output code is generated. If lines are added\n# or removed, the anchors will not be placed correctly.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# properly processed by doxygen.\n\nINPUT_FILTER           =\n\n# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern\n# basis. Doxygen will compare the file name with each pattern and apply the\n# filter if there is a match. The filters are a list of the form: pattern=filter\n# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how\n# filters are used. If the FILTER_PATTERNS tag is empty or if none of the\n# patterns match the file name, INPUT_FILTER is applied.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# properly processed by doxygen.\n\nFILTER_PATTERNS        =\n\n# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using\n# INPUT_FILTER) will also be used to filter the input files that are used for\n# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).\n# The default value is: NO.\n\nFILTER_SOURCE_FILES    = NO\n\n# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file\n# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and\n# it is also possible to disable source filtering for a specific pattern using\n# *.ext= (so without naming a filter).\n# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.\n\nFILTER_SOURCE_PATTERNS =\n\n# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that\n# is part of the input, its contents will be placed on the main page\n# (index.html). This can be useful if you have a project on for instance GitHub\n# and want to reuse the introduction page also for the doxygen output.\n\nUSE_MDFILE_AS_MAINPAGE = README.md\n\n#---------------------------------------------------------------------------\n# Configuration options related to source browsing\n#---------------------------------------------------------------------------\n\n# If the SOURCE_BROWSER tag is set to YES then a list of source files will be\n# generated. Documented entities will be cross-referenced with these sources.\n#\n# Note: To get rid of all source code in the generated output, make sure that\n# also VERBATIM_HEADERS is set to NO.\n# The default value is: NO.\n\nSOURCE_BROWSER         = NO\n\n# Setting the INLINE_SOURCES tag to YES will include the body of functions,\n# classes and enums directly into the documentation.\n# The default value is: NO.\n\nINLINE_SOURCES         = NO\n\n# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any\n# special comment blocks from generated source code fragments. Normal C, C++ and\n# Fortran comments will always remain visible.\n# The default value is: YES.\n\nSTRIP_CODE_COMMENTS    = YES\n\n# If the REFERENCED_BY_RELATION tag is set to YES then for each documented\n# entity all documented functions referencing it will be listed.\n# The default value is: NO.\n\nREFERENCED_BY_RELATION = NO\n\n# If the REFERENCES_RELATION tag is set to YES then for each documented function\n# all documented entities called/used by that function will be listed.\n# The default value is: NO.\n\nREFERENCES_RELATION    = NO\n\n# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set\n# to YES then the hyperlinks from functions in REFERENCES_RELATION and\n# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will\n# link to the documentation.\n# The default value is: YES.\n\nREFERENCES_LINK_SOURCE = YES\n\n# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the\n# source code will show a tooltip with additional information such as prototype,\n# brief description and links to the definition and documentation. Since this\n# will make the HTML file larger and loading of large files a bit slower, you\n# can opt to disable this feature.\n# The default value is: YES.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nSOURCE_TOOLTIPS        = YES\n\n# If the USE_HTAGS tag is set to YES then the references to source code will\n# point to the HTML generated by the htags(1) tool instead of doxygen built-in\n# source browser. The htags tool is part of GNU's global source tagging system\n# (see https://www.gnu.org/software/global/global.html). You will need version\n# 4.8.6 or higher.\n#\n# To use it do the following:\n# - Install the latest version of global\n# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file\n# - Make sure the INPUT points to the root of the source tree\n# - Run doxygen as normal\n#\n# Doxygen will invoke htags (and that will in turn invoke gtags), so these\n# tools must be available from the command line (i.e. in the search path).\n#\n# The result: instead of the source browser generated by doxygen, the links to\n# source code will now point to the output of htags.\n# The default value is: NO.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nUSE_HTAGS              = NO\n\n# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a\n# verbatim copy of the header file for each class for which an include is\n# specified. Set to NO to disable this.\n# See also: Section \\class.\n# The default value is: YES.\n\nVERBATIM_HEADERS       = YES\n\n# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the\n# clang parser (see:\n# http://clang.llvm.org/) for more accurate parsing at the cost of reduced\n# performance. This can be particularly helpful with template rich C++ code for\n# which doxygen's built-in parser lacks the necessary type information.\n# Note: The availability of this option depends on whether or not doxygen was\n# generated with the -Duse_libclang=ON option for CMake.\n# The default value is: NO.\n\nCLANG_ASSISTED_PARSING = NO\n\n# If clang assisted parsing is enabled and the CLANG_ADD_INC_PATHS tag is set to\n# YES then doxygen will add the directory of each input to the include path.\n# The default value is: YES.\n\nCLANG_ADD_INC_PATHS    = YES\n\n# If clang assisted parsing is enabled you can provide the compiler with command\n# line options that you would normally use when invoking the compiler. Note that\n# the include paths will already be set by doxygen for the files and directories\n# specified with INPUT and INCLUDE_PATH.\n# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.\n\nCLANG_OPTIONS          =\n\n# If clang assisted parsing is enabled you can provide the clang parser with the\n# path to the directory containing a file called compile_commands.json. This\n# file is the compilation database (see:\n# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) containing the\n# options used when the source files were built. This is equivalent to\n# specifying the -p option to a clang tool, such as clang-check. These options\n# will then be passed to the parser. Any options specified with CLANG_OPTIONS\n# will be added as well.\n# Note: The availability of this option depends on whether or not doxygen was\n# generated with the -Duse_libclang=ON option for CMake.\n\nCLANG_DATABASE_PATH    =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the alphabetical class index\n#---------------------------------------------------------------------------\n\n# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all\n# compounds will be generated. Enable this if the project contains a lot of\n# classes, structs, unions or interfaces.\n# The default value is: YES.\n\nALPHABETICAL_INDEX     = YES\n\n# In case all classes in a project start with a common prefix, all classes will\n# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag\n# can be used to specify a prefix (or a list of prefixes) that should be ignored\n# while generating the index headers.\n# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.\n\nIGNORE_PREFIX          =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the HTML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output\n# The default value is: YES.\n\nGENERATE_HTML          = YES\n\n# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_OUTPUT            = html\n\n# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each\n# generated HTML page (for example: .htm, .php, .asp).\n# The default value is: .html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FILE_EXTENSION    = .html\n\n# The HTML_HEADER tag can be used to specify a user-defined HTML header file for\n# each generated HTML page. If the tag is left blank doxygen will generate a\n# standard header.\n#\n# To get valid HTML the header file that includes any scripts and style sheets\n# that doxygen needs, which is dependent on the configuration options used (e.g.\n# the setting GENERATE_TREEVIEW). It is highly recommended to start with a\n# default header using\n# doxygen -w html new_header.html new_footer.html new_stylesheet.css\n# YourConfigFile\n# and then modify the file new_header.html. See also section \"Doxygen usage\"\n# for information on how to generate the default header that doxygen normally\n# uses.\n# Note: The header is subject to change so you typically have to regenerate the\n# default header when upgrading to a newer version of doxygen. For a description\n# of the possible markers and block names see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_HEADER            =\n\n# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each\n# generated HTML page. If the tag is left blank doxygen will generate a standard\n# footer. See HTML_HEADER for more information on how to generate a default\n# footer and what special commands can be used inside the footer. See also\n# section \"Doxygen usage\" for information on how to generate the default footer\n# that doxygen normally uses.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FOOTER            =\n\n# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style\n# sheet that is used by each HTML page. It can be used to fine-tune the look of\n# the HTML output. If left blank doxygen will generate a default style sheet.\n# See also section \"Doxygen usage\" for information on how to generate the style\n# sheet that doxygen normally uses.\n# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as\n# it is more robust and this tag (HTML_STYLESHEET) will in the future become\n# obsolete.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_STYLESHEET        =\n\n# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined\n# cascading style sheets that are included after the standard style sheets\n# created by doxygen. Using this option one can overrule certain style aspects.\n# This is preferred over using HTML_STYLESHEET since it does not replace the\n# standard style sheet and is therefore more robust against future updates.\n# Doxygen will copy the style sheet files to the output directory.\n# Note: The order of the extra style sheet files is of importance (e.g. the last\n# style sheet in the list overrules the setting of the previous ones in the\n# list). For an example see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_STYLESHEET  =\n\n# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the HTML output directory. Note\n# that these files will be copied to the base HTML output directory. Use the\n# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these\n# files. In the HTML_STYLESHEET file, use the file name only. Also note that the\n# files will be copied as-is; there are no commands or markers available.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_FILES       =\n\n# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen\n# will adjust the colors in the style sheet and background images according to\n# this color. Hue is specified as an angle on a colorwheel, see\n# https://en.wikipedia.org/wiki/Hue for more information. For instance the value\n# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300\n# purple, and 360 is red again.\n# Minimum value: 0, maximum value: 359, default value: 220.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_HUE    = 220\n\n# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors\n# in the HTML output. For a value of 0 the output will use grayscales only. A\n# value of 255 will produce the most vivid colors.\n# Minimum value: 0, maximum value: 255, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_SAT    = 100\n\n# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the\n# luminance component of the colors in the HTML output. Values below 100\n# gradually make the output lighter, whereas values above 100 make the output\n# darker. The value divided by 100 is the actual gamma applied, so 80 represents\n# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not\n# change the gamma.\n# Minimum value: 40, maximum value: 240, default value: 80.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_GAMMA  = 80\n\n# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML\n# page will contain the date and time when the page was generated. Setting this\n# to YES can help to show when doxygen was last run and thus if the\n# documentation is up to date.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_TIMESTAMP         = NO\n\n# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML\n# documentation will contain a main index with vertical navigation menus that\n# are dynamically created via JavaScript. If disabled, the navigation index will\n# consists of multiple levels of tabs that are statically embedded in every HTML\n# page. Disable this option to support browsers that do not have JavaScript,\n# like the Qt help browser.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_DYNAMIC_MENUS     = YES\n\n# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML\n# documentation will contain sections that can be hidden and shown after the\n# page has loaded.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_DYNAMIC_SECTIONS  = NO\n\n# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries\n# shown in the various tree structured indices initially; the user can expand\n# and collapse entries dynamically later on. Doxygen will expand the tree to\n# such a level that at most the specified number of entries are visible (unless\n# a fully collapsed tree already exceeds this amount). So setting the number of\n# entries 1 will produce a full collapsed tree by default. 0 is a special value\n# representing an infinite number of entries and will result in a full expanded\n# tree by default.\n# Minimum value: 0, maximum value: 9999, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_INDEX_NUM_ENTRIES = 100\n\n# If the GENERATE_DOCSET tag is set to YES, additional index files will be\n# generated that can be used as input for Apple's Xcode 3 integrated development\n# environment (see:\n# https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To\n# create a documentation set, doxygen will generate a Makefile in the HTML\n# output directory. Running make will produce the docset in that directory and\n# running make install will install the docset in\n# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at\n# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy\n# genXcode/_index.html for more information.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_DOCSET        = NO\n\n# This tag determines the name of the docset feed. A documentation feed provides\n# an umbrella under which multiple documentation sets from a single provider\n# (such as a company or product suite) can be grouped.\n# The default value is: Doxygen generated docs.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_FEEDNAME        = \"Doxygen generated docs\"\n\n# This tag specifies a string that should uniquely identify the documentation\n# set bundle. This should be a reverse domain-name style string, e.g.\n# com.mycompany.MyDocSet. Doxygen will append .docset to the name.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_BUNDLE_ID       = org.doxygen.Project\n\n# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify\n# the documentation publisher. This should be a reverse domain-name style\n# string, e.g. com.mycompany.MyDocSet.documentation.\n# The default value is: org.doxygen.Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_ID    = org.doxygen.Publisher\n\n# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.\n# The default value is: Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_NAME  = Publisher\n\n# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three\n# additional HTML index files: index.hhp, index.hhc, and index.hhk. The\n# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop\n# (see:\n# https://www.microsoft.com/en-us/download/details.aspx?id=21138) on Windows.\n#\n# The HTML Help Workshop contains a compiler that can convert all HTML output\n# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML\n# files are now used as the Windows 98 help format, and will replace the old\n# Windows help format (.hlp) on all Windows platforms in the future. Compressed\n# HTML files also contain an index, a table of contents, and you can search for\n# words in the documentation. The HTML workshop also contains a viewer for\n# compressed HTML files.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_HTMLHELP      = NO\n\n# The CHM_FILE tag can be used to specify the file name of the resulting .chm\n# file. You can add a path in front of the file if the result should not be\n# written to the html output directory.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_FILE               =\n\n# The HHC_LOCATION tag can be used to specify the location (absolute path\n# including file name) of the HTML help compiler (hhc.exe). If non-empty,\n# doxygen will try to run the HTML help compiler on the generated index.hhp.\n# The file has to be specified with full path.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nHHC_LOCATION           =\n\n# The GENERATE_CHI flag controls if a separate .chi index file is generated\n# (YES) or that it should be included in the main .chm file (NO).\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nGENERATE_CHI           = NO\n\n# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)\n# and project file content.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_INDEX_ENCODING     =\n\n# The BINARY_TOC flag controls whether a binary table of contents is generated\n# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it\n# enables the Previous and Next buttons.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nBINARY_TOC             = NO\n\n# The TOC_EXPAND flag can be set to YES to add extra items for group members to\n# the table of contents of the HTML help documentation and to the tree view.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nTOC_EXPAND             = NO\n\n# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and\n# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that\n# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help\n# (.qch) of the generated HTML documentation.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_QHP           = NO\n\n# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify\n# the file name of the resulting .qch file. The path specified is relative to\n# the HTML output folder.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQCH_FILE               =\n\n# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help\n# Project output. For more information please see Qt Help Project / Namespace\n# (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_NAMESPACE          = org.doxygen.Project\n\n# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt\n# Help Project output. For more information please see Qt Help Project / Virtual\n# Folders (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders).\n# The default value is: doc.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_VIRTUAL_FOLDER     = doc\n\n# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom\n# filter to add. For more information please see Qt Help Project / Custom\n# Filters (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_NAME   =\n\n# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the\n# custom filter to add. For more information please see Qt Help Project / Custom\n# Filters (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_ATTRS  =\n\n# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this\n# project's filter section matches. Qt Help Project / Filter Attributes (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_SECT_FILTER_ATTRS  =\n\n# The QHG_LOCATION tag can be used to specify the location (absolute path\n# including file name) of Qt's qhelpgenerator. If non-empty doxygen will try to\n# run qhelpgenerator on the generated .qhp file.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHG_LOCATION           =\n\n# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be\n# generated, together with the HTML files, they form an Eclipse help plugin. To\n# install this plugin and make it available under the help contents menu in\n# Eclipse, the contents of the directory containing the HTML and XML files needs\n# to be copied into the plugins directory of eclipse. The name of the directory\n# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.\n# After copying Eclipse needs to be restarted before the help appears.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_ECLIPSEHELP   = NO\n\n# A unique identifier for the Eclipse help plugin. When installing the plugin\n# the directory name containing the HTML and XML files should also have this\n# name. Each documentation set should have its own identifier.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.\n\nECLIPSE_DOC_ID         = org.doxygen.Project\n\n# If you want full control over the layout of the generated HTML pages it might\n# be necessary to disable the index and replace it with your own. The\n# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top\n# of each HTML page. A value of NO enables the index and the value YES disables\n# it. Since the tabs in the index contain the same information as the navigation\n# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nDISABLE_INDEX          = NO\n\n# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index\n# structure should be generated to display hierarchical information. If the tag\n# value is set to YES, a side panel will be generated containing a tree-like\n# index structure (just like the one that is generated for HTML Help). For this\n# to work a browser that supports JavaScript, DHTML, CSS and frames is required\n# (i.e. any modern browser). Windows users are probably better off using the\n# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can\n# further fine-tune the look of the index. As an example, the default style\n# sheet generated by doxygen has an example that shows how to put an image at\n# the root of the tree instead of the PROJECT_NAME. Since the tree basically has\n# the same information as the tab index, you could consider setting\n# DISABLE_INDEX to YES when enabling this option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_TREEVIEW      = NO\n\n# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that\n# doxygen will group on one line in the generated HTML documentation.\n#\n# Note that a value of 0 will completely suppress the enum values from appearing\n# in the overview section.\n# Minimum value: 0, maximum value: 20, default value: 4.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nENUM_VALUES_PER_LINE   = 4\n\n# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used\n# to set the initial width (in pixels) of the frame in which the tree is shown.\n# Minimum value: 0, maximum value: 1500, default value: 250.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nTREEVIEW_WIDTH         = 250\n\n# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to\n# external symbols imported via tag files in a separate window.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nEXT_LINKS_IN_WINDOW    = NO\n\n# If the HTML_FORMULA_FORMAT option is set to svg, doxygen will use the pdf2svg\n# tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see\n# https://inkscape.org) to generate formulas as SVG images instead of PNGs for\n# the HTML output. These images will generally look nicer at scaled resolutions.\n# Possible values are: png (the default) and svg (looks nicer but requires the\n# pdf2svg or inkscape tool).\n# The default value is: png.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FORMULA_FORMAT    = png\n\n# Use this tag to change the font size of LaTeX formulas included as images in\n# the HTML documentation. When you change the font size after a successful\n# doxygen run you need to manually remove any form_*.png images from the HTML\n# output directory to force them to be regenerated.\n# Minimum value: 8, maximum value: 50, default value: 10.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_FONTSIZE       = 10\n\n# Use the FORMULA_TRANSPARENT tag to determine whether or not the images\n# generated for formulas are transparent PNGs. Transparent PNGs are not\n# supported properly for IE 6.0, but are supported on all modern browsers.\n#\n# Note that when changing this option you need to delete any form_*.png files in\n# the HTML output directory before the changes have effect.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_TRANSPARENT    = YES\n\n# The FORMULA_MACROFILE can contain LaTeX \\newcommand and \\renewcommand commands\n# to create new LaTeX commands to be used in formulas as building blocks. See\n# the section \"Including formulas\" for details.\n\nFORMULA_MACROFILE      =\n\n# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see\n# https://www.mathjax.org) which uses client side JavaScript for the rendering\n# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX\n# installed or if you want to formulas look prettier in the HTML output. When\n# enabled you may also need to install MathJax separately and configure the path\n# to it using the MATHJAX_RELPATH option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nUSE_MATHJAX            = NO\n\n# When MathJax is enabled you can set the default output format to be used for\n# the MathJax output. See the MathJax site (see:\n# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details.\n# Possible values are: HTML-CSS (which is slower, but has the best\n# compatibility), NativeMML (i.e. MathML) and SVG.\n# The default value is: HTML-CSS.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_FORMAT         = HTML-CSS\n\n# When MathJax is enabled you need to specify the location relative to the HTML\n# output directory using the MATHJAX_RELPATH option. The destination directory\n# should contain the MathJax.js script. For instance, if the mathjax directory\n# is located at the same level as the HTML output directory, then\n# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax\n# Content Delivery Network so you can quickly see the result without installing\n# MathJax. However, it is strongly recommended to install a local copy of\n# MathJax from https://www.mathjax.org before deployment.\n# The default value is: https://cdn.jsdelivr.net/npm/mathjax@2.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_RELPATH        = https://cdn.jsdelivr.net/npm/mathjax@2\n\n# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax\n# extension names that should be enabled during MathJax rendering. For example\n# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_EXTENSIONS     =\n\n# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces\n# of code that will be used on startup of the MathJax code. See the MathJax site\n# (see:\n# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. For an\n# example see the documentation.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_CODEFILE       =\n\n# When the SEARCHENGINE tag is enabled doxygen will generate a search box for\n# the HTML output. The underlying search engine uses javascript and DHTML and\n# should work on any modern browser. Note that when using HTML help\n# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)\n# there is already a search function so this one should typically be disabled.\n# For large projects the javascript based search engine can be slow, then\n# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to\n# search using the keyboard; to jump to the search box use <access key> + S\n# (what the <access key> is depends on the OS and browser, but it is typically\n# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down\n# key> to jump into the search results window, the results can be navigated\n# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel\n# the search. The filter options can be selected when the cursor is inside the\n# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>\n# to select a filter and <Enter> or <escape> to activate or cancel the filter\n# option.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nSEARCHENGINE           = YES\n\n# When the SERVER_BASED_SEARCH tag is enabled the search engine will be\n# implemented using a web server instead of a web client using JavaScript. There\n# are two flavors of web server based searching depending on the EXTERNAL_SEARCH\n# setting. When disabled, doxygen will generate a PHP script for searching and\n# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing\n# and searching needs to be provided by external tools. See the section\n# \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSERVER_BASED_SEARCH    = NO\n\n# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP\n# script for searching. Instead the search results are written to an XML file\n# which needs to be processed by an external indexer. Doxygen will invoke an\n# external search engine pointed to by the SEARCHENGINE_URL option to obtain the\n# search results.\n#\n# Doxygen ships with an example indexer (doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see:\n# https://xapian.org/).\n#\n# See the section \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH        = NO\n\n# The SEARCHENGINE_URL should point to a search engine hosted by a web server\n# which will return the search results when EXTERNAL_SEARCH is enabled.\n#\n# Doxygen ships with an example indexer (doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see:\n# https://xapian.org/). See the section \"External Indexing and Searching\" for\n# details.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHENGINE_URL       =\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed\n# search data is written to a file for indexing by an external tool. With the\n# SEARCHDATA_FILE tag the name of this file can be specified.\n# The default file is: searchdata.xml.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHDATA_FILE        = searchdata.xml\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the\n# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is\n# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple\n# projects and redirect the results back to the right project.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH_ID     =\n\n# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen\n# projects other than the one defined by this configuration file, but that are\n# all added to the same external search index. Each project needs to have a\n# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of\n# to a relative location where the documentation can be found. The format is:\n# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTRA_SEARCH_MAPPINGS  =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the LaTeX output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.\n# The default value is: YES.\n\nGENERATE_LATEX         = NO\n\n# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: latex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_OUTPUT           = latex\n\n# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be\n# invoked.\n#\n# Note that when not enabling USE_PDFLATEX the default is latex when enabling\n# USE_PDFLATEX the default is pdflatex and when in the later case latex is\n# chosen this is overwritten by pdflatex. For specific output languages the\n# default can have been set differently, this depends on the implementation of\n# the output language.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_CMD_NAME         =\n\n# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate\n# index for LaTeX.\n# Note: This tag is used in the Makefile / make.bat.\n# See also: LATEX_MAKEINDEX_CMD for the part in the generated output file\n# (.tex).\n# The default file is: makeindex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nMAKEINDEX_CMD_NAME     = makeindex\n\n# The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to\n# generate index for LaTeX. In case there is no backslash (\\) as first character\n# it will be automatically added in the LaTeX code.\n# Note: This tag is used in the generated output file (.tex).\n# See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat.\n# The default value is: makeindex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_MAKEINDEX_CMD    = makeindex\n\n# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nCOMPACT_LATEX          = NO\n\n# The PAPER_TYPE tag can be used to set the paper type that is used by the\n# printer.\n# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x\n# 14 inches) and executive (7.25 x 10.5 inches).\n# The default value is: a4.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPAPER_TYPE             = a4\n\n# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names\n# that should be included in the LaTeX output. The package can be specified just\n# by its name or with the correct syntax as to be used with the LaTeX\n# \\usepackage command. To get the times font for instance you can specify :\n# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}\n# To use the option intlimits with the amsmath package you can specify:\n# EXTRA_PACKAGES=[intlimits]{amsmath}\n# If left blank no extra packages will be included.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nEXTRA_PACKAGES         =\n\n# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the\n# generated LaTeX document. The header should contain everything until the first\n# chapter. If it is left blank doxygen will generate a standard header. See\n# section \"Doxygen usage\" for information on how to let doxygen write the\n# default header to a separate file.\n#\n# Note: Only use a user-defined header if you know what you are doing! The\n# following commands have a special meaning inside the header: $title,\n# $datetime, $date, $doxygenversion, $projectname, $projectnumber,\n# $projectbrief, $projectlogo. Doxygen will replace $title with the empty\n# string, for the replacement values of the other commands the user is referred\n# to HTML_HEADER.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HEADER           =\n\n# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the\n# generated LaTeX document. The footer should contain everything after the last\n# chapter. If it is left blank doxygen will generate a standard footer. See\n# LATEX_HEADER for more information on how to generate a default footer and what\n# special commands can be used inside the footer.\n#\n# Note: Only use a user-defined footer if you know what you are doing!\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_FOOTER           =\n\n# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined\n# LaTeX style sheets that are included after the standard style sheets created\n# by doxygen. Using this option one can overrule certain style aspects. Doxygen\n# will copy the style sheet files to the output directory.\n# Note: The order of the extra style sheet files is of importance (e.g. the last\n# style sheet in the list overrules the setting of the previous ones in the\n# list).\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_STYLESHEET =\n\n# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the LATEX_OUTPUT output\n# directory. Note that the files will be copied as-is; there are no commands or\n# markers available.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_FILES      =\n\n# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is\n# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will\n# contain links (just like the HTML output) instead of page references. This\n# makes the output suitable for online browsing using a PDF viewer.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPDF_HYPERLINKS         = YES\n\n# If the USE_PDFLATEX tag is set to YES, doxygen will use the engine as\n# specified with LATEX_CMD_NAME to generate the PDF file directly from the LaTeX\n# files. Set this option to YES, to get a higher quality PDF documentation.\n#\n# See also section LATEX_CMD_NAME for selecting the engine.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nUSE_PDFLATEX           = YES\n\n# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode\n# command to the generated LaTeX files. This will instruct LaTeX to keep running\n# if errors occur, instead of asking the user for help. This option is also used\n# when generating formulas in HTML.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BATCHMODE        = NO\n\n# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the\n# index chapters (such as File Index, Compound Index, etc.) in the output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HIDE_INDICES     = NO\n\n# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source\n# code with syntax highlighting in the LaTeX output.\n#\n# Note that which sources are shown also depends on other settings such as\n# SOURCE_BROWSER.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_SOURCE_CODE      = NO\n\n# The LATEX_BIB_STYLE tag can be used to specify the style to use for the\n# bibliography, e.g. plainnat, or ieeetr. See\n# https://en.wikipedia.org/wiki/BibTeX and \\cite for more info.\n# The default value is: plain.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BIB_STYLE        = plain\n\n# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated\n# page will contain the date and time when the page was generated. Setting this\n# to NO can help when comparing the output of multiple runs.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_TIMESTAMP        = NO\n\n# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute)\n# path from which the emoji images will be read. If a relative path is entered,\n# it will be relative to the LATEX_OUTPUT directory. If left blank the\n# LATEX_OUTPUT directory will be used.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EMOJI_DIRECTORY  =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the RTF output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The\n# RTF output is optimized for Word 97 and may not look too pretty with other RTF\n# readers/editors.\n# The default value is: NO.\n\nGENERATE_RTF           = NO\n\n# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: rtf.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_OUTPUT             = rtf\n\n# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nCOMPACT_RTF            = NO\n\n# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will\n# contain hyperlink fields. The RTF file will contain links (just like the HTML\n# output) instead of page references. This makes the output suitable for online\n# browsing using Word or some other Word compatible readers that support those\n# fields.\n#\n# Note: WordPad (write) and others do not support links.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_HYPERLINKS         = NO\n\n# Load stylesheet definitions from file. Syntax is similar to doxygen's\n# configuration file, i.e. a series of assignments. You only have to provide\n# replacements, missing definitions are set to their default value.\n#\n# See also section \"Doxygen usage\" for information on how to generate the\n# default style sheet that doxygen normally uses.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_STYLESHEET_FILE    =\n\n# Set optional variables used in the generation of an RTF document. Syntax is\n# similar to doxygen's configuration file. A template extensions file can be\n# generated using doxygen -e rtf extensionFile.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_EXTENSIONS_FILE    =\n\n# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code\n# with syntax highlighting in the RTF output.\n#\n# Note that which sources are shown also depends on other settings such as\n# SOURCE_BROWSER.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_SOURCE_CODE        = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the man page output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for\n# classes and files.\n# The default value is: NO.\n\nGENERATE_MAN           = NO\n\n# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it. A directory man3 will be created inside the directory specified by\n# MAN_OUTPUT.\n# The default directory is: man.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_OUTPUT             = man\n\n# The MAN_EXTENSION tag determines the extension that is added to the generated\n# man pages. In case the manual section does not start with a number, the number\n# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is\n# optional.\n# The default value is: .3.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_EXTENSION          = .3\n\n# The MAN_SUBDIR tag determines the name of the directory created within\n# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by\n# MAN_EXTENSION with the initial . removed.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_SUBDIR             =\n\n# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it\n# will generate one additional man file for each entity documented in the real\n# man page(s). These additional files only source the real man page, but without\n# them the man command would be unable to find the correct page.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_LINKS              = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the XML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that\n# captures the structure of the code including all documentation.\n# The default value is: NO.\n\nGENERATE_XML           = NO\n\n# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: xml.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_OUTPUT             = xml\n\n# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program\n# listings (including syntax highlighting and cross-referencing information) to\n# the XML output. Note that enabling this will significantly increase the size\n# of the XML output.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_PROGRAMLISTING     = YES\n\n# If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include\n# namespace members in file scope as well, matching the HTML output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_NS_MEMB_FILE_SCOPE = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the DOCBOOK output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files\n# that can be used to generate PDF.\n# The default value is: NO.\n\nGENERATE_DOCBOOK       = NO\n\n# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in\n# front of it.\n# The default directory is: docbook.\n# This tag requires that the tag GENERATE_DOCBOOK is set to YES.\n\nDOCBOOK_OUTPUT         = docbook\n\n# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the\n# program listings (including syntax highlighting and cross-referencing\n# information) to the DOCBOOK output. Note that enabling this will significantly\n# increase the size of the DOCBOOK output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_DOCBOOK is set to YES.\n\nDOCBOOK_PROGRAMLISTING = NO\n\n#---------------------------------------------------------------------------\n# Configuration options for the AutoGen Definitions output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an\n# AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures\n# the structure of the code including all documentation. Note that this feature\n# is still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_AUTOGEN_DEF   = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the Perl module output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module\n# file that captures the structure of the code including all documentation.\n#\n# Note that this feature is still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_PERLMOD       = NO\n\n# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary\n# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI\n# output from the Perl module output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_LATEX          = NO\n\n# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely\n# formatted so it can be parsed by a human reader. This is useful if you want to\n# understand what is going on. On the other hand, if this tag is set to NO, the\n# size of the Perl module output will be much smaller and Perl will parse it\n# just the same.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_PRETTY         = YES\n\n# The names of the make variables in the generated doxyrules.make file are\n# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful\n# so different doxyrules.make files included by the same Makefile don't\n# overwrite each other's variables.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_MAKEVAR_PREFIX =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the preprocessor\n#---------------------------------------------------------------------------\n\n# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all\n# C-preprocessor directives found in the sources and include files.\n# The default value is: YES.\n\nENABLE_PREPROCESSING   = YES\n\n# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names\n# in the source code. If set to NO, only conditional compilation will be\n# performed. Macro expansion can be done in a controlled way by setting\n# EXPAND_ONLY_PREDEF to YES.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nMACRO_EXPANSION        = NO\n\n# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then\n# the macro expansion is limited to the macros specified with the PREDEFINED and\n# EXPAND_AS_DEFINED tags.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_ONLY_PREDEF     = NO\n\n# If the SEARCH_INCLUDES tag is set to YES, the include files in the\n# INCLUDE_PATH will be searched if a #include is found.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSEARCH_INCLUDES        = YES\n\n# The INCLUDE_PATH tag can be used to specify one or more directories that\n# contain include files that are not input files but should be processed by the\n# preprocessor.\n# This tag requires that the tag SEARCH_INCLUDES is set to YES.\n\nINCLUDE_PATH           =\n\n# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard\n# patterns (like *.h and *.hpp) to filter out the header-files in the\n# directories. If left blank, the patterns specified with FILE_PATTERNS will be\n# used.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nINCLUDE_FILE_PATTERNS  =\n\n# The PREDEFINED tag can be used to specify one or more macro names that are\n# defined before the preprocessor is started (similar to the -D option of e.g.\n# gcc). The argument of the tag is a list of macros of the form: name or\n# name=definition (no spaces). If the definition and the \"=\" are omitted, \"=1\"\n# is assumed. To prevent a macro definition from being undefined via #undef or\n# recursively expanded use the := operator instead of the = operator.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nPREDEFINED             = INJECTOR_DOC\n\n# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this\n# tag can be used to specify a list of macro names that should be expanded. The\n# macro definition that is found in the sources will be used. Use the PREDEFINED\n# tag if you want to use a different macro definition that overrules the\n# definition found in the source code.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_AS_DEFINED      =\n\n# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will\n# remove all references to function-like macros that are alone on a line, have\n# an all uppercase name, and do not end with a semicolon. Such function macros\n# are typically used for boiler-plate code, and will confuse the parser if not\n# removed.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSKIP_FUNCTION_MACROS   = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to external references\n#---------------------------------------------------------------------------\n\n# The TAGFILES tag can be used to specify one or more tag files. For each tag\n# file the location of the external documentation should be added. The format of\n# a tag file without this location is as follows:\n# TAGFILES = file1 file2 ...\n# Adding location for the tag files is done as follows:\n# TAGFILES = file1=loc1 \"file2 = loc2\" ...\n# where loc1 and loc2 can be relative or absolute paths or URLs. See the\n# section \"Linking to external documentation\" for more information about the use\n# of tag files.\n# Note: Each tag file must have a unique name (where the name does NOT include\n# the path). If a tag file is not located in the directory in which doxygen is\n# run, you must also specify the path to the tagfile here.\n\nTAGFILES               =\n\n# When a file name is specified after GENERATE_TAGFILE, doxygen will create a\n# tag file that is based on the input files it reads. See section \"Linking to\n# external documentation\" for more information about the usage of tag files.\n\nGENERATE_TAGFILE       =\n\n# If the ALLEXTERNALS tag is set to YES, all external class will be listed in\n# the class index. If set to NO, only the inherited external classes will be\n# listed.\n# The default value is: NO.\n\nALLEXTERNALS           = NO\n\n# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed\n# in the modules index. If set to NO, only the current project's groups will be\n# listed.\n# The default value is: YES.\n\nEXTERNAL_GROUPS        = YES\n\n# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in\n# the related pages index. If set to NO, only the current project's pages will\n# be listed.\n# The default value is: YES.\n\nEXTERNAL_PAGES         = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to the dot tool\n#---------------------------------------------------------------------------\n\n# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram\n# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to\n# NO turns the diagrams off. Note that this option also works with HAVE_DOT\n# disabled, but it is recommended to install and use dot, since it yields more\n# powerful graphs.\n# The default value is: YES.\n\nCLASS_DIAGRAMS         = YES\n\n# You can include diagrams made with dia in doxygen documentation. Doxygen will\n# then run dia to produce the diagram and insert it in the documentation. The\n# DIA_PATH tag allows you to specify the directory where the dia binary resides.\n# If left empty dia is assumed to be found in the default search path.\n\nDIA_PATH               =\n\n# If set to YES the inheritance and collaboration graphs will hide inheritance\n# and usage relations if the target is undocumented or is not a class.\n# The default value is: YES.\n\nHIDE_UNDOC_RELATIONS   = YES\n\n# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is\n# available from the path. This tool is part of Graphviz (see:\n# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent\n# Bell Labs. The other options in this section have no effect if this option is\n# set to NO\n# The default value is: YES.\n\nHAVE_DOT               = YES\n\n# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed\n# to run in parallel. When set to 0 doxygen will base this on the number of\n# processors available in the system. You can set it explicitly to a value\n# larger than 0 to get control over the balance between CPU load and processing\n# speed.\n# Minimum value: 0, maximum value: 32, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_NUM_THREADS        = 0\n\n# When you want a differently looking font in the dot files that doxygen\n# generates you can specify the font name using DOT_FONTNAME. You need to make\n# sure dot is able to find the font, which can be done by putting it in a\n# standard location or by setting the DOTFONTPATH environment variable or by\n# setting DOT_FONTPATH to the directory containing the font.\n# The default value is: Helvetica.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTNAME           = Helvetica\n\n# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of\n# dot graphs.\n# Minimum value: 4, maximum value: 24, default value: 10.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTSIZE           = 10\n\n# By default doxygen will tell dot to use the default font as specified with\n# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set\n# the path where dot can find it using this tag.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTPATH           =\n\n# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for\n# each documented class showing the direct and indirect inheritance relations.\n# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCLASS_GRAPH            = YES\n\n# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a\n# graph for each documented class showing the direct and indirect implementation\n# dependencies (inheritance, containment, and class references variables) of the\n# class with other documented classes.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCOLLABORATION_GRAPH    = YES\n\n# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for\n# groups, showing the direct groups dependencies.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGROUP_GRAPHS           = YES\n\n# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and\n# collaboration diagrams in a style similar to the OMG's Unified Modeling\n# Language.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nUML_LOOK               = NO\n\n# If the UML_LOOK tag is enabled, the fields and methods are shown inside the\n# class node. If there are many fields or methods and many nodes the graph may\n# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the\n# number of items for each type to make the size more manageable. Set this to 0\n# for no limit. Note that the threshold may be exceeded by 50% before the limit\n# is enforced. So when you set the threshold to 10, up to 15 fields may appear,\n# but if the number exceeds 15, the total amount of fields shown is limited to\n# 10.\n# Minimum value: 0, maximum value: 100, default value: 10.\n# This tag requires that the tag UML_LOOK is set to YES.\n\nUML_LIMIT_NUM_FIELDS   = 10\n\n# If the DOT_UML_DETAILS tag is set to NO, doxygen will show attributes and\n# methods without types and arguments in the UML graphs. If the DOT_UML_DETAILS\n# tag is set to YES, doxygen will add type and arguments for attributes and\n# methods in the UML graphs. If the DOT_UML_DETAILS tag is set to NONE, doxygen\n# will not generate fields with class member information in the UML graphs. The\n# class diagrams will look similar to the default class diagrams but using UML\n# notation for the relationships.\n# Possible values are: NO, YES and NONE.\n# The default value is: NO.\n# This tag requires that the tag UML_LOOK is set to YES.\n\nDOT_UML_DETAILS        = NO\n\n# The DOT_WRAP_THRESHOLD tag can be used to set the maximum number of characters\n# to display on a single line. If the actual line length exceeds this threshold\n# significantly it will wrapped across multiple lines. Some heuristics are apply\n# to avoid ugly line breaks.\n# Minimum value: 0, maximum value: 1000, default value: 17.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_WRAP_THRESHOLD     = 17\n\n# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and\n# collaboration graphs will show the relations between templates and their\n# instances.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nTEMPLATE_RELATIONS     = NO\n\n# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to\n# YES then doxygen will generate a graph for each documented file showing the\n# direct and indirect include dependencies of the file with other documented\n# files.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDE_GRAPH          = YES\n\n# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are\n# set to YES then doxygen will generate a graph for each documented file showing\n# the direct and indirect include dependencies of the file with other documented\n# files.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDED_BY_GRAPH      = YES\n\n# If the CALL_GRAPH tag is set to YES then doxygen will generate a call\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable call graphs for selected\n# functions only using the \\callgraph command. Disabling a call graph can be\n# accomplished by means of the command \\hidecallgraph.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALL_GRAPH             = NO\n\n# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable caller graphs for selected\n# functions only using the \\callergraph command. Disabling a caller graph can be\n# accomplished by means of the command \\hidecallergraph.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALLER_GRAPH           = NO\n\n# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical\n# hierarchy of all classes instead of a textual one.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGRAPHICAL_HIERARCHY    = YES\n\n# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the\n# dependencies a directory has on other directories in a graphical way. The\n# dependency relations are determined by the #include relations between the\n# files in the directories.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDIRECTORY_GRAPH        = YES\n\n# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images\n# generated by dot. For an explanation of the image formats see the section\n# output formats in the documentation of the dot tool (Graphviz (see:\n# http://www.graphviz.org/)).\n# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order\n# to make the SVG files visible in IE 9+ (other browsers do not have this\n# requirement).\n# Possible values are: png, png:cairo, png:cairo:cairo, png:cairo:gd, png:gd,\n# png:gd:gd, jpg, jpg:cairo, jpg:cairo:gd, jpg:gd, jpg:gd:gd, gif, gif:cairo,\n# gif:cairo:gd, gif:gd, gif:gd:gd, svg, png:gd, png:gd:gd, png:cairo,\n# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and\n# png:gdiplus:gdiplus.\n# The default value is: png.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_IMAGE_FORMAT       = png\n\n# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to\n# enable generation of interactive SVG images that allow zooming and panning.\n#\n# Note that this requires a modern browser other than Internet Explorer. Tested\n# and working are Firefox, Chrome, Safari, and Opera.\n# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make\n# the SVG files visible. Older versions of IE do not have SVG support.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINTERACTIVE_SVG        = NO\n\n# The DOT_PATH tag can be used to specify the path where the dot tool can be\n# found. If left blank, it is assumed the dot tool can be found in the path.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_PATH               =\n\n# The DOTFILE_DIRS tag can be used to specify one or more directories that\n# contain dot files that are included in the documentation (see the \\dotfile\n# command).\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOTFILE_DIRS           =\n\n# The MSCFILE_DIRS tag can be used to specify one or more directories that\n# contain msc files that are included in the documentation (see the \\mscfile\n# command).\n\nMSCFILE_DIRS           =\n\n# The DIAFILE_DIRS tag can be used to specify one or more directories that\n# contain dia files that are included in the documentation (see the \\diafile\n# command).\n\nDIAFILE_DIRS           =\n\n# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the\n# path where java can find the plantuml.jar file. If left blank, it is assumed\n# PlantUML is not used or called during a preprocessing step. Doxygen will\n# generate a warning when it encounters a \\startuml command in this case and\n# will not generate output for the diagram.\n\nPLANTUML_JAR_PATH      =\n\n# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a\n# configuration file for plantuml.\n\nPLANTUML_CFG_FILE      =\n\n# When using plantuml, the specified paths are searched for files specified by\n# the !include statement in a plantuml block.\n\nPLANTUML_INCLUDE_PATH  =\n\n# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes\n# that will be shown in the graph. If the number of nodes in a graph becomes\n# larger than this value, doxygen will truncate the graph, which is visualized\n# by representing a node as a red box. Note that doxygen if the number of direct\n# children of the root node in a graph is already larger than\n# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that\n# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.\n# Minimum value: 0, maximum value: 10000, default value: 50.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_GRAPH_MAX_NODES    = 50\n\n# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs\n# generated by dot. A depth value of 3 means that only nodes reachable from the\n# root by following a path via at most 3 edges will be shown. Nodes that lay\n# further from the root node will be omitted. Note that setting this option to 1\n# or 2 may greatly reduce the computation time needed for large code bases. Also\n# note that the size of a graph can be further restricted by\n# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.\n# Minimum value: 0, maximum value: 1000, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nMAX_DOT_GRAPH_DEPTH    = 0\n\n# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent\n# background. This is disabled by default, because dot on Windows does not seem\n# to support this out of the box.\n#\n# Warning: Depending on the platform used, enabling this option may lead to\n# badly anti-aliased labels on the edges of a graph (i.e. they become hard to\n# read).\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_TRANSPARENT        = NO\n\n# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output\n# files in one run (i.e. multiple -o and -T options on the command line). This\n# makes dot run faster, but since only newer versions of dot (>1.8.10) support\n# this, this feature is disabled by default.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_MULTI_TARGETS      = NO\n\n# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page\n# explaining the meaning of the various boxes and arrows in the dot generated\n# graphs.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGENERATE_LEGEND        = YES\n\n# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate\n# files that are used to generate the various graphs.\n#\n# Note: This setting is not only used for dot files but also for msc and\n# plantuml temporary files.\n# The default value is: YES.\n\nDOT_CLEANUP            = YES\n"
  },
  {
    "path": "LICENSE_GPL.txt",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n"
  },
  {
    "path": "LICENSE_LGPL.txt",
    "content": "                  GNU LESSER GENERAL PUBLIC LICENSE\n                       Version 2.1, February 1999\n\n Copyright (C) 1991, 1999 Free Software Foundation, Inc.\n 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n[This is the first released version of the Lesser GPL.  It also counts\n as the successor of the GNU Library Public License, version 2, hence\n the version number 2.1.]\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicenses are intended to guarantee your freedom to share and change\nfree software--to make sure the software is free for all its users.\n\n  This license, the Lesser General Public License, applies to some\nspecially designated software packages--typically libraries--of the\nFree Software Foundation and other authors who decide to use it.  You\ncan use it too, but we suggest you first think carefully about whether\nthis license or the ordinary General Public License is the better\nstrategy to use in any particular case, based on the explanations below.\n\n  When we speak of free software, we are referring to freedom of use,\nnot price.  Our General Public Licenses are designed to make sure that\nyou have the freedom to distribute copies of free software (and charge\nfor this service if you wish); that you receive source code or can get\nit if you want it; that you can change the software and use pieces of\nit in new free programs; and that you are informed that you can do\nthese things.\n\n  To protect your rights, we need to make restrictions that forbid\ndistributors to deny you these rights or to ask you to surrender these\nrights.  These restrictions translate to certain responsibilities for\nyou if you distribute copies of the library or if you modify it.\n\n  For example, if you distribute copies of the library, whether gratis\nor for a fee, you must give the recipients all the rights that we gave\nyou.  You must make sure that they, too, receive or can get the source\ncode.  If you link other code with the library, you must provide\ncomplete object files to the recipients, so that they can relink them\nwith the library after making changes to the library and recompiling\nit.  And you must show them these terms so they know their rights.\n\n  We protect your rights with a two-step method: (1) we copyright the\nlibrary, and (2) we offer you this license, which gives you legal\npermission to copy, distribute and/or modify the library.\n\n  To protect each distributor, we want to make it very clear that\nthere is no warranty for the free library.  Also, if the library is\nmodified by someone else and passed on, the recipients should know\nthat what they have is not the original version, so that the original\nauthor's reputation will not be affected by problems that might be\nintroduced by others.\n\f\n  Finally, software patents pose a constant threat to the existence of\nany free program.  We wish to make sure that a company cannot\neffectively restrict the users of a free program by obtaining a\nrestrictive license from a patent holder.  Therefore, we insist that\nany patent license obtained for a version of the library must be\nconsistent with the full freedom of use specified in this license.\n\n  Most GNU software, including some libraries, is covered by the\nordinary GNU General Public License.  This license, the GNU Lesser\nGeneral Public License, applies to certain designated libraries, and\nis quite different from the ordinary General Public License.  We use\nthis license for certain libraries in order to permit linking those\nlibraries into non-free programs.\n\n  When a program is linked with a library, whether statically or using\na shared library, the combination of the two is legally speaking a\ncombined work, a derivative of the original library.  The ordinary\nGeneral Public License therefore permits such linking only if the\nentire combination fits its criteria of freedom.  The Lesser General\nPublic License permits more lax criteria for linking other code with\nthe library.\n\n  We call this license the \"Lesser\" General Public License because it\ndoes Less to protect the user's freedom than the ordinary General\nPublic License.  It also provides other free software developers Less\nof an advantage over competing non-free programs.  These disadvantages\nare the reason we use the ordinary General Public License for many\nlibraries.  However, the Lesser license provides advantages in certain\nspecial circumstances.\n\n  For example, on rare occasions, there may be a special need to\nencourage the widest possible use of a certain library, so that it becomes\na de-facto standard.  To achieve this, non-free programs must be\nallowed to use the library.  A more frequent case is that a free\nlibrary does the same job as widely used non-free libraries.  In this\ncase, there is little to gain by limiting the free library to free\nsoftware only, so we use the Lesser General Public License.\n\n  In other cases, permission to use a particular library in non-free\nprograms enables a greater number of people to use a large body of\nfree software.  For example, permission to use the GNU C Library in\nnon-free programs enables many more people to use the whole GNU\noperating system, as well as its variant, the GNU/Linux operating\nsystem.\n\n  Although the Lesser General Public License is Less protective of the\nusers' freedom, it does ensure that the user of a program that is\nlinked with the Library has the freedom and the wherewithal to run\nthat program using a modified version of the Library.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.  Pay close attention to the difference between a\n\"work based on the library\" and a \"work that uses the library\".  The\nformer contains code derived from the library, whereas the latter must\nbe combined with the library in order to run.\n\f\n                  GNU LESSER GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License Agreement applies to any software library or other\nprogram which contains a notice placed by the copyright holder or\nother authorized party saying it may be distributed under the terms of\nthis Lesser General Public License (also called \"this License\").\nEach licensee is addressed as \"you\".\n\n  A \"library\" means a collection of software functions and/or data\nprepared so as to be conveniently linked with application programs\n(which use some of those functions and data) to form executables.\n\n  The \"Library\", below, refers to any such software library or work\nwhich has been distributed under these terms.  A \"work based on the\nLibrary\" means either the Library or any derivative work under\ncopyright law: that is to say, a work containing the Library or a\nportion of it, either verbatim or with modifications and/or translated\nstraightforwardly into another language.  (Hereinafter, translation is\nincluded without limitation in the term \"modification\".)\n\n  \"Source code\" for a work means the preferred form of the work for\nmaking modifications to it.  For a library, complete source code means\nall the source code for all modules it contains, plus any associated\ninterface definition files, plus the scripts used to control compilation\nand installation of the library.\n\n  Activities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning a program using the Library is not restricted, and output from\nsuch a program is covered only if its contents constitute a work based\non the Library (independent of the use of the Library in a tool for\nwriting it).  Whether that is true depends on what the Library does\nand what the program that uses the Library does.\n\n  1. You may copy and distribute verbatim copies of the Library's\ncomplete source code as you receive it, in any medium, provided that\nyou conspicuously and appropriately publish on each copy an\nappropriate copyright notice and disclaimer of warranty; keep intact\nall the notices that refer to this License and to the absence of any\nwarranty; and distribute a copy of this License along with the\nLibrary.\n\n  You may charge a fee for the physical act of transferring a copy,\nand you may at your option offer warranty protection in exchange for a\nfee.\n\f\n  2. You may modify your copy or copies of the Library or any portion\nof it, thus forming a work based on the Library, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) The modified work must itself be a software library.\n\n    b) You must cause the files modified to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    c) You must cause the whole of the work to be licensed at no\n    charge to all third parties under the terms of this License.\n\n    d) If a facility in the modified Library refers to a function or a\n    table of data to be supplied by an application program that uses\n    the facility, other than as an argument passed when the facility\n    is invoked, then you must make a good faith effort to ensure that,\n    in the event an application does not supply such function or\n    table, the facility still operates, and performs whatever part of\n    its purpose remains meaningful.\n\n    (For example, a function in a library to compute square roots has\n    a purpose that is entirely well-defined independent of the\n    application.  Therefore, Subsection 2d requires that any\n    application-supplied function or table used by this function must\n    be optional: if the application does not supply it, the square\n    root function must still compute square roots.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Library,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Library, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote\nit.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Library.\n\nIn addition, mere aggregation of another work not based on the Library\nwith the Library (or with a work based on the Library) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may opt to apply the terms of the ordinary GNU General Public\nLicense instead of this License to a given copy of the Library.  To do\nthis, you must alter all the notices that refer to this License, so\nthat they refer to the ordinary GNU General Public License, version 2,\ninstead of to this License.  (If a newer version than version 2 of the\nordinary GNU General Public License has appeared, then you can specify\nthat version instead if you wish.)  Do not make any other change in\nthese notices.\n\f\n  Once this change is made in a given copy, it is irreversible for\nthat copy, so the ordinary GNU General Public License applies to all\nsubsequent copies and derivative works made from that copy.\n\n  This option is useful when you wish to copy part of the code of\nthe Library into a program that is not a library.\n\n  4. You may copy and distribute the Library (or a portion or\nderivative of it, under Section 2) in object code or executable form\nunder the terms of Sections 1 and 2 above provided that you accompany\nit with the complete corresponding machine-readable source code, which\nmust be distributed under the terms of Sections 1 and 2 above on a\nmedium customarily used for software interchange.\n\n  If distribution of object code is made by offering access to copy\nfrom a designated place, then offering equivalent access to copy the\nsource code from the same place satisfies the requirement to\ndistribute the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  5. A program that contains no derivative of any portion of the\nLibrary, but is designed to work with the Library by being compiled or\nlinked with it, is called a \"work that uses the Library\".  Such a\nwork, in isolation, is not a derivative work of the Library, and\ntherefore falls outside the scope of this License.\n\n  However, linking a \"work that uses the Library\" with the Library\ncreates an executable that is a derivative of the Library (because it\ncontains portions of the Library), rather than a \"work that uses the\nlibrary\".  The executable is therefore covered by this License.\nSection 6 states terms for distribution of such executables.\n\n  When a \"work that uses the Library\" uses material from a header file\nthat is part of the Library, the object code for the work may be a\nderivative work of the Library even though the source code is not.\nWhether this is true is especially significant if the work can be\nlinked without the Library, or if the work is itself a library.  The\nthreshold for this to be true is not precisely defined by law.\n\n  If such an object file uses only numerical parameters, data\nstructure layouts and accessors, and small macros and small inline\nfunctions (ten lines or less in length), then the use of the object\nfile is unrestricted, regardless of whether it is legally a derivative\nwork.  (Executables containing this object code plus portions of the\nLibrary will still fall under Section 6.)\n\n  Otherwise, if the work is a derivative of the Library, you may\ndistribute the object code for the work under the terms of Section 6.\nAny executables containing that work also fall under Section 6,\nwhether or not they are linked directly with the Library itself.\n\f\n  6. As an exception to the Sections above, you may also combine or\nlink a \"work that uses the Library\" with the Library to produce a\nwork containing portions of the Library, and distribute that work\nunder terms of your choice, provided that the terms permit\nmodification of the work for the customer's own use and reverse\nengineering for debugging such modifications.\n\n  You must give prominent notice with each copy of the work that the\nLibrary is used in it and that the Library and its use are covered by\nthis License.  You must supply a copy of this License.  If the work\nduring execution displays copyright notices, you must include the\ncopyright notice for the Library among them, as well as a reference\ndirecting the user to the copy of this License.  Also, you must do one\nof these things:\n\n    a) Accompany the work with the complete corresponding\n    machine-readable source code for the Library including whatever\n    changes were used in the work (which must be distributed under\n    Sections 1 and 2 above); and, if the work is an executable linked\n    with the Library, with the complete machine-readable \"work that\n    uses the Library\", as object code and/or source code, so that the\n    user can modify the Library and then relink to produce a modified\n    executable containing the modified Library.  (It is understood\n    that the user who changes the contents of definitions files in the\n    Library will not necessarily be able to recompile the application\n    to use the modified definitions.)\n\n    b) Use a suitable shared library mechanism for linking with the\n    Library.  A suitable mechanism is one that (1) uses at run time a\n    copy of the library already present on the user's computer system,\n    rather than copying library functions into the executable, and (2)\n    will operate properly with a modified version of the library, if\n    the user installs one, as long as the modified version is\n    interface-compatible with the version that the work was made with.\n\n    c) Accompany the work with a written offer, valid for at\n    least three years, to give the same user the materials\n    specified in Subsection 6a, above, for a charge no more\n    than the cost of performing this distribution.\n\n    d) If distribution of the work is made by offering access to copy\n    from a designated place, offer equivalent access to copy the above\n    specified materials from the same place.\n\n    e) Verify that the user has already received a copy of these\n    materials or that you have already sent this user a copy.\n\n  For an executable, the required form of the \"work that uses the\nLibrary\" must include any data and utility programs needed for\nreproducing the executable from it.  However, as a special exception,\nthe materials to be distributed need not include anything that is\nnormally distributed (in either source or binary form) with the major\ncomponents (compiler, kernel, and so on) of the operating system on\nwhich the executable runs, unless that component itself accompanies\nthe executable.\n\n  It may happen that this requirement contradicts the license\nrestrictions of other proprietary libraries that do not normally\naccompany the operating system.  Such a contradiction means you cannot\nuse both them and the Library together in an executable that you\ndistribute.\n\f\n  7. You may place library facilities that are a work based on the\nLibrary side-by-side in a single library together with other library\nfacilities not covered by this License, and distribute such a combined\nlibrary, provided that the separate distribution of the work based on\nthe Library and of the other library facilities is otherwise\npermitted, and provided that you do these two things:\n\n    a) Accompany the combined library with a copy of the same work\n    based on the Library, uncombined with any other library\n    facilities.  This must be distributed under the terms of the\n    Sections above.\n\n    b) Give prominent notice with the combined library of the fact\n    that part of it is a work based on the Library, and explaining\n    where to find the accompanying uncombined form of the same work.\n\n  8. You may not copy, modify, sublicense, link with, or distribute\nthe Library except as expressly provided under this License.  Any\nattempt otherwise to copy, modify, sublicense, link with, or\ndistribute the Library is void, and will automatically terminate your\nrights under this License.  However, parties who have received copies,\nor rights, from you under this License will not have their licenses\nterminated so long as such parties remain in full compliance.\n\n  9. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Library or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Library (or any work based on the\nLibrary), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Library or works based on it.\n\n  10. Each time you redistribute the Library (or any work based on the\nLibrary), the recipient automatically receives a license from the\noriginal licensor to copy, distribute, link with or modify the Library\nsubject to these terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties with\nthis License.\n\f\n  11. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Library at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Library by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Library.\n\nIf any portion of this section is held invalid or unenforceable under any\nparticular circumstance, the balance of the section is intended to apply,\nand the section as a whole is intended to apply in other circumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  12. If the distribution and/or use of the Library is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Library under this License may add\nan explicit geographical distribution limitation excluding those countries,\nso that distribution is permitted only in or among countries not thus\nexcluded.  In such case, this License incorporates the limitation as if\nwritten in the body of this License.\n\n  13. The Free Software Foundation may publish revised and/or new\nversions of the Lesser General Public License from time to time.\nSuch new versions will be similar in spirit to the present version,\nbut may differ in detail to address new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Library\nspecifies a version number of this License which applies to it and\n\"any later version\", you have the option of following the terms and\nconditions either of that version or of any later version published by\nthe Free Software Foundation.  If the Library does not specify a\nlicense version number, you may choose any version ever published by\nthe Free Software Foundation.\n\f\n  14. If you wish to incorporate parts of the Library into other free\nprograms whose distribution conditions are incompatible with these,\nwrite to the author to ask for permission.  For software which is\ncopyrighted by the Free Software Foundation, write to the Free\nSoftware Foundation; we sometimes make exceptions for this.  Our\ndecision will be guided by the two goals of preserving the free status\nof all derivatives of our free software and of promoting the sharing\nand reuse of software generally.\n\n                            NO WARRANTY\n\n  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\nWARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\nEXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\nOTHER PARTIES PROVIDE THE LIBRARY \"AS IS\" WITHOUT WARRANTY OF ANY\nKIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\nLIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\nTHE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\nWRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\nAND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\nFOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\nCONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\nLIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\nRENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\nFAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\nSUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\nDAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n"
  },
  {
    "path": "Makefile",
    "content": "ifeq ($(OS),Windows_NT)\n  SRC_DIR = src/windows\nelse\n  UNAME_S := $(shell uname -s)\n  ifeq ($(UNAME_S),Darwin)\n    SRC_DIR = src/macos\n  else\n    SRC_DIR = src/linux\n  endif\nendif\n\nall:\n\tcd $(SRC_DIR) && $(MAKE)\n\tcd cmd && $(MAKE)\n\ncheck:\n\tcd tests && $(MAKE) check\n\nclean:\n\tcd $(SRC_DIR) && $(MAKE) clean\n\tcd cmd && $(MAKE) clean\n\tcd tests && $(MAKE) clean\n"
  },
  {
    "path": "Makefile.win32",
    "content": "\nRTFLAG = -MD  # link with dynamic runtime library\n# RTFLAG = -MT  # link with static runtime library\n\nMAKE_CMD = nmake -nologo -f Makefile.win32 RTFLAG=$(RTFLAG) ARM64EC=$(ARM64EC)\n\nall:\n\tcd src/windows && $(MAKE_CMD)\n\tcd cmd && $(MAKE_CMD)\n\ncheck: all\n\tcd tests && $(MAKE_CMD) check\n\nclean:\n\tcd src/windows && $(MAKE_CMD) clean\n\tcd cmd && $(MAKE_CMD) clean\n\tcd tests && $(MAKE_CMD) clean\n"
  },
  {
    "path": "README.md",
    "content": "# Injector\n\n[![Static Badge](https://img.shields.io/badge/docs-API_reference-blue)](http://www.jiubao.org/injector/injector_8h.html)\n\n**Library for injecting a shared library into a Linux, Windows and MacOS process**\n\n> [!CAUTION]  \n> Due to a shift in my personal interests, this repository is no longer maintained and has been archived.\n> If you're looking for a successor project, please check [the network graph](https://github.com/kubo/injector/network) to see if any forks have continued development.\n\n## Linux\n\n> [!WARNING]  \n> Don't use this in production environments. It may stop target processes forever. See [Caveats](#caveats).\n\nI was inspired by [`linux-inject`][] and the basic idea came from it.\nHowever the way to call `__libc_dlopen_mode` in `libc.so.6` is\nthoroughly different.\n\n* `linux-inject` writes about 80 bytes of code to the target process\n  on x86_64. This writes only 4 ~ 16 bytes.\n* `linux-inject` writes code at the firstly found executable region\n  of memory, which may be referred by other threads. This writes it\n  at [the entry point of `libc.so.6`][libc_main], which will be referred by\n  nobody unless the libc itself is executed as a program.\n\n[libc_main]: https://sourceware.org/git/?p=glibc.git;a=blob;f=csu/version.c;h=8c0ed79c01223e1f12b54d19f90b5e5b7dd78d27;hb=c804cd1c00adde061ca51711f63068c103e94eef#l67\n\n## Windows\n\nWindows version is also here. It uses well-known [`CreateRemoteThread+LoadLibrary`]\ntechnique to load a DLL into another process with some improvements.\n\n1. It gets Win32 error messages when `LoadLibrary` fails by copying assembly\n   code into the target process.\n2. It can inject a 32-bit dll into a 32-bit process from x64 processes\n   by checking the export entries in 32-bit kernel32.dll.\n\n**Note:** It may work on Windows on ARM though I have not tested it because\nI have no ARM machines. Let me know if it really works.\n\n## MacOS\nThe injector connects to the target process using task_for_pid and creates a mach-thread. If dlopen is called in this thread, the target process will fail with an error, however, it is possible to create another thread using pthread_create_from_mach_thread function for Mac >= 10.12 or pthread_create otherwise. In the created thread, the code for loading the library is executed. The second thread is created when injector_inject is called and terminated when injector_detach is called.\n# Compilation\n\n## Linux\n\n```shell\n$ git clone https://github.com/kubo/injector.git\n$ cd injector\n$ make\n```\n\nThe `make` command creates:\n\n| filename | - |\n|---|---|\n|`src/linux/libinjector.a`  |a static library|\n|`src/linux/libinjector.so` |a shared library|\n|`cmd/injector`             |a command line program linked with the static library|\n\n## Windows (MSVC)\n\nOpen a Visual Studio command prompt and run the following commands:\n\n```shell\n$ git clone https://github.com/kubo/injector.git # Or use any other tool\n$ cd injector\n$ nmake -f Makefile.win32\n```\n\nThe `nmake` command creates:\n\n| filename | - |\n|---|---|\n|`src/windows/injector-static.lib`  |a static library (release build)\n|`src/windows/injector.dll`         |a shared library (release build)\n|`src/windows/injector.lib`         |an import library for `injector.dll`\n|`src/windows/injectord-static.lib` |a static library (debug build)\n|`src/windows/injectord.dll`        |a shared library (debug build)\n|`src/windows/injectord.lib`        |an import library for `injectord.dll`\n|`cmd/injector.exe`                 |a command line program linked the static library (release build)|\n\n## Windows (mingw-w64)\n\nOn MSYS2:\n\n```shell\n$ git clone https://github.com/kubo/injector.git\n$ cd injector\n$ CC=gcc make\n```\n\nCross-compilation on Linux:\n\n```shell\n$ git clone https://github.com/kubo/injector.git\n$ cd injector\n$ CC=x86_64-w64-mingw32-gcc OS=Windows_NT make\n```\n\nThe environment variable `OS=Windows_NT` must be set on Linux.\n\n## MacOS\n\n```shell\n$ git clone https://github.com/TheOiseth/injector.git\n$ cd injector\n$ make\n```\n\nThe `make` command creates:\n\n| filename | - |\n|---|---|\n|`src/macos/libinjector.a`  |a static library|\n|`src/macos/libinjector.dylib` |a shared library|\n|`cmd/injector`             |a command line program linked with the static library|\n\n**Important:** in order for the injector process to connect to another process using task_for_pid, it is necessary to [`disable SIP`][] or sign the injector with a self-signed certificate with debugging permission, for this:\n```shell\n$ cd cmd/macos-sign\n$ chmod +x genkey.sh\n$ ./genkey.sh\n$ chmod +x sign.sh\n$ ./sign.sh\n```\nIf injector still does not work after signing, reboot the system.\n\n# Usage\n\n## C API\n\n```c\n#include <injector.h>\n\n...\n\n    injector_t *injector;\n    void *handle;\n\n    /* attach to a process whose process id is 1234. */\n    if (injector_attach(&injector, 1234) != 0) {\n        printf(\"ATTACH ERROR: %s\\n\", injector_error());\n        return;\n    }\n    /* inject a shared library into the process. */\n    if (injector_inject(injector, \"/path/to/shared/library\", NULL) != 0) {\n        printf(\"INJECT ERROR: %s\\n\", injector_error());\n    }\n    /* inject another shared library. */\n    if (injector_inject(injector, \"/path/to/another/shared/library\", &handle) != 0) {\n        printf(\"INJECT ERROR: %s\\n\", injector_error());\n    }\n\n...\n\n    /* uninject the second shared library. */\n    if (injector_uninject(injector, handle) != 0) {\n        printf(\"UNINJECT ERROR: %s\\n\", injector_error());\n    }\n\n    /* cleanup */\n    injector_detach(injector);\n```\n\n## Command line program\n\nSee [`Usage` section and `Sample` section in linux-inject][`inject`] and substitute\n`inject` with `injector` in the page.\n\n# Tested Architectures\n\n## Linux\n\nx86_64:\n\ninjector process \\ target process | x86_64 | i386 | x32(*1)\n---|---|---|---\n**x86_64** | :smiley: success(*2) | :smiley: success(*3) | :smiley: success(*6)\n**i386**   | :skull:  failure(*4) | :smiley: success(*3) | :skull:  failure(*5)\n**x32**(*1) | :skull:  failure(*4) | :smiley: success(*6) | :skull:  failure(*5)\n\n*1: [x32 ABI](https://en.wikipedia.org/wiki/X32_ABI)  \n*2: tested on github actions with both glibc and musl.  \n*3: tested on github actions with glibc.  \n*4: failure with `64-bit target process isn't supported by 32-bit process`.  \n*5: failure with `x32-ABI target process is supported only by x86_64`.  \n*6: tested on a local machine. `CONFIG_X86_X32` isn't enabled in github actions.  \n\nARM:\n\ninjector process \\ target process | arm64 | armhf | armel\n---|---|---|---\n**arm64** | :smiley: success     | :smiley: success | :smiley: success\n**armhf** | :skull:  failure(*1) | :smiley: success | :smiley: success\n**armel** | :skull:  failure(*1) | :smiley: success | :smiley: success\n\n*1: failure with `64-bit target process isn't supported by 32-bit process`.  \n\nMIPS:\n\ninjector process \\ target process | mips64el | mipsel (n32) | mipsel (o32)\n---|---|---|---\n**mips64el** | :smiley: success (*1)    | :smiley: success (*1) | :smiley: success (*1)\n**mipsel (n32)** | :skull:  failure(*2) | :smiley: success (*1) | :smiley: success (*1)\n**mipsel (o32)** | :skull:  failure(*2) | :smiley: success (*1) | :smiley: success (*1)\n\n*1: tested on [debian 11 mips64el](https://www.debian.org/releases/bullseye/mips64el/ch02s01.en.html#idm271) on [QEMU](https://www.qemu.org/).  \n*2: failure with `64-bit target process isn't supported by 32-bit process`.  \n\nPowerPC:\n\n* **ppc64le** (tested on [alpine 3.16.2 ppc64le](https://dl-cdn.alpinelinux.org/alpine/v3.16/releases/ppc64le/) on [QEMU](https://www.qemu.org/))\n* **powerpc (big endian)** (tested on [ubuntu 16.04 powerpc](https://old-releases.ubuntu.com/releases/xenial/) on [QEMU](https://www.qemu.org/)\n\nRISC-V:\n\n* **riscv64** (tested on [Ubuntu 22.04.1 riscv64 on QEMU](https://wiki.ubuntu.com/RISC-V#Booting_with_QEMU))\n\n## Windows\n\nWindows x64:\n\ninjector process \\ target process | x64 | x86\n---|---|---\n**x64**     | :smiley: success(*2) | :smiley: success(*2)\n**x86**     | :skull:  failure(*1) | :smiley: success(*2)\n\n*1: failure with `x64 target process isn't supported by x86 process`.  \n*2: tested on github actions  \n\nWindows 11 on Arm:\n\ninjector process \\ target process | arm64 | arm64ec | x64 | x86 | arm32\n---|---|---|---|---|---\n**arm64**   | :smiley: success | :skull:  failure | :skull:  failure | :skull:  failure | :smiley: success\n**arm64ec** | :skull:  failure | :smiley: success | :smiley: success | :skull:  failure | :skull:  failure\n**x64**     | :skull:  failure | :smiley: success | :smiley: success | :skull:  failure | :skull:  failure\n**x86**     | :skull:  failure | :skull:  failure | :skull:  failure | :smiley: success | :skull:  failure\n**arm32**   | :skull:  failure | :skull:  failure | :skull:  failure | :skull:  failure | :smiley: success\n\n[Wine](https://www.winehq.org/) (on Linux x86_64):\n\ninjector process \\ target process | x64 | x86\n---|---|---\n**x64**     | :smiley: success | :skull:  failure\n**x86**     | :skull:  failure | :smiley: success\n\n## MacOS\n\ninjector process \\ target process | x64 | arm64\n---|---|---\n**x64**     | :smiley: success(*1) | :skull:  failure(*2)\n**arm64**   | :skull:  failure(*3) | :smiley: success\n\n*1: failure with `x86_64 target process isn't supported by x86_64 process on ARM64 machine`. Tested on github actions.  \n*2: failure with `arm64 target process isn't supported by x86_64 process.`  \n*3: failure with `x86_64 target process isn't supported by arm64 process.`\n\n# Caveats\n\n**The following restrictions are only on Linux.**\n\nInjector doesn't work where `ptrace()` is disallowed.\n\n* Non-children processes (See [Caveat about `ptrace()`][])\n* Docker containers on docker version < 19.03 or linux kernel version < 4.8. You need to pass [`--cap-add=SYS_PTRACE`](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities)\nto `docker run` to allow it in the environments.\n* Linux inside of UserLAnd (Android App) (See [here](https://github.com/kubo/injector/issues/17#issuecomment-1113990177))\n\nInjector calls functions inside of a target process interrupted by `ptrace()`.\nIf the target process is interrupted while holding a non-reentrant lock and\ninjector calls a function requiring the same lock, the process stops forever.\nIf the lock type is reentrant, the status guarded by the lock may become inconsistent.\nAs far as I checked, `dlopen()` internally calls `malloc()` requiring non-reentrant\nlocks. `dlopen()` also uses a reentrant lock to guard information about loaded files.\n\nOn Linux x86_64 `injector_inject_in_cloned_thread` in place of `injector_inject`\nmay be a solution of the locking issue. It calls `dlopen()` in a thread created by\n[`clone()`]. Note that no wonder there are unexpected pitfalls because some resources\nallocated in [`pthread_create()`] lack in the `clone()`-ed thread. Use it at\nyour own risk.\n\n# License\n\nFiles under [`include`][] and [`src`][] are licensed under LGPL 2.1 or later.  \nFiles under [`cmd`][] are licensed under GPL 2 or later.  \nFiles under [`util`][] are licensed under 2-clause BSD.\n\n[`linux-inject`]: https://github.com/gaffe23/linux-inject\n[Caveat about `ptrace()`]: https://github.com/gaffe23/linux-inject#caveat-about-ptrace\n[`inject`]: https://github.com/gaffe23/linux-inject#usage\n[`clone()`]: https://man7.org/linux/man-pages/man2/clone.2.html\n[`cmd`]: cmd\n[`include`]: include\n[`pthread_create()`]: https://man7.org/linux/man-pages/man3/pthread_create.3.html\n[`src`]: src\n[`util`]: util\n[`CreateRemoteThread+LoadLibrary`]: https://www.google.com/search?&q=CreateRemoteThread+LoadLIbrary\n[`disable SIP`]: https://developer.apple.com/documentation/security/disabling_and_enabling_system_integrity_protection\n"
  },
  {
    "path": "cmd/Makefile",
    "content": "CFLAGS = -Wall -I../include\nOBJS = main.o\nLIBS =\n\nifeq ($(OS),Windows_NT)\n  SRC_DIR = ../src/windows\n  LIBS += -ldbghelp\n  OBJS += ya_getopt.o\nelse\n  UNAME_S := $(shell uname -s)\n  ifeq ($(UNAME_S),Darwin)\n    SRC_DIR = ../src/macos\n    OBJS += ya_getopt.o\n  else\n    SRC_DIR = ../src/linux\n  endif\nendif\n\nall: injector\n\ninjector: $(OBJS) $(SRC_DIR)/libinjector.a\n\t$(CC) -o injector $(OBJS) $(SRC_DIR)/libinjector.a $(LIBS)\n\nmain.o: main.c\nya_getopt.o: ../util/ya_getopt.c\n\t$(CC) $(CFLAGS) -c ../util/ya_getopt.c\n$(SRC_DIR)/libinjlib.a:\n\tcd $(SRC_DIR) && $(MAKE)\n\nclean:\n\t$(RM) injector $(OBJS)\n"
  },
  {
    "path": "cmd/Makefile.win32",
    "content": "# -*- Makefile -*-\n\nRTFLAG = -MD  # link with dynamic runtime library\n# RTFLAG = -MT  # link with static runtime library\n\nCFLAGS = -nologo $(RTFLAG) -I../include\n\n!IF \"$(ARM64EC)\" != \"\"\nCFLAGS = $(CFLAGS) -arm64EC\n!ENDIF\n\nOBJS = main.obj ya_getopt.obj\nINJECTOR_LIB = ..\\src\\windows\\injector-static.lib\n\nall: injector.exe\n\ninjector.exe: $(OBJS) $(INJECTOR_LIB)\n\t$(CC) $(CFLAGS) -Feinjector.exe $(OBJS) $(INJECTOR_LIB)\n\nmain.obj: main.c\n\t$(CC) $(CFLAGS) -c main.c\nya_getopt.obj: ..\\util\\ya_getopt.c\n\t$(CC) $(CFLAGS) -c ..\\util\\ya_getopt.c\n$(INJECTOR_LIB):\n\tcd ..\\src\\windows && nmake -f Makefile.win32\n\nclean:\n\tdel injector.exe $(OBJS)\n"
  },
  {
    "path": "cmd/macos-sign/entitlement.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n    <key>com.apple.security.cs.debugger</key>\n    <true/>\n</dict>\n</plist>\n</pre>"
  },
  {
    "path": "cmd/macos-sign/genkey.sh",
    "content": "#!/bin/bash\n\n# This script is copied from https://github.com/llvm/llvm-project/blob/main/lldb/scripts/macos-setup-codesign.sh\nif test -z \"$1\" \nthen\nCERT=\"injector-key\"\nelse\nCERT=\"$1\"\nfi\n\n\nfunction error() {\n    echo error: \"$@\" 1>&2\n    exit 1\n}\n\nfunction cleanup {\n    # Remove generated files\n    rm -f \"$TMPDIR/$CERT.tmpl\" \"$TMPDIR/$CERT.cer\" \"$TMPDIR/$CERT.key\" > /dev/null 2>&1\n}\n\ntrap cleanup EXIT\n\n# Check if the certificate is already present in the system keychain\nsecurity find-certificate -Z -p -c \"$CERT\" /Library/Keychains/System.keychain > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n    echo Certificate has already been generated and installed\n    exit 0\nfi\n\n# Create the certificate template\ncat <<EOF >$TMPDIR/$CERT.tmpl\n[ req ]\ndefault_bits       = 2048        # RSA key size\nencrypt_key        = no          # Protect private key\ndefault_md         = sha512      # MD to use\nprompt             = no          # Prompt for DN\ndistinguished_name = codesign_dn # DN template\n[ codesign_dn ]\ncommonName         = \"$CERT\"\n[ codesign_reqext ]\nkeyUsage           = critical,digitalSignature\nextendedKeyUsage   = critical,codeSigning\nEOF\n\necho Generating and installing \"$CERT\" certificate\n\n# Generate a new certificate\nopenssl req -new -newkey rsa:2048 -x509 -days 3650 -nodes -config \"$TMPDIR/$CERT.tmpl\" -extensions codesign_reqext -batch -out \"$TMPDIR/$CERT.cer\" -keyout \"$TMPDIR/$CERT.key\" > /dev/null 2>&1\n[ $? -eq 0 ] || error Something went wrong when generating the certificate\n\n# Install the certificate in the system keychain\nsudo security authorizationdb read com.apple.trust-settings.admin > \"$TMPDIR/rights\"\nsudo security authorizationdb write com.apple.trust-settings.admin allow\nsudo security add-trusted-cert -d -r trustRoot -p codeSign -k /Library/Keychains/System.keychain \"$TMPDIR/$CERT.cer\" > /dev/null 2>&1\nresult=$?\nsudo security authorizationdb write com.apple.trust-settings.admin < \"$TMPDIR/rights\"\n[ $result -eq 0 ] || error Something went wrong when installing the certificate\n\n# Install the key for the certificate in the system keychain\nsudo security import \"$TMPDIR/$CERT.key\" -A -k /Library/Keychains/System.keychain > /dev/null 2>&1\n[ $? -eq 0 ] || error Something went wrong when installing the key\n\n# Kill task_for_pid access control daemon\nsudo pkill -f /usr/libexec/taskgated > /dev/null 2>&1\n\n# Exit indicating the certificate is now generated and installed\nexit 0"
  },
  {
    "path": "cmd/macos-sign/sign.sh",
    "content": "#!/bin/bash\nif test -z \"$1\" \nthen\nkey=\"injector-key\"\nelse\nkey=\"$1\"\nfi\n\nif test -z \"$2\" \nthen\nexecutable=\"../injector\"\nelse\nexecutable=\"$2\"\nfi\n\n/usr/bin/codesign --entitlements entitlement.xml --force --sign \"$key\" \"$executable\""
  },
  {
    "path": "cmd/main.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2018 Kubo Takehiro <kubo@jiubao.org>\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of\n * the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"injector.h\"\n\n#ifdef __linux\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <limits.h>\n\n#define INVALID_PID -1\nstatic pid_t find_process(const char *name)\n{\n    DIR *dir = opendir(\"/proc\");\n    struct dirent *dent;\n    pid_t pid = -1;\n\n    if (dir == NULL) {\n        fprintf(stderr, \"Failed to read proc file system.\\n\");\n        exit(1);\n    }\n    while ((dent = readdir(dir)) != NULL) {\n        char path[sizeof(dent->d_name) + 11];\n        char exepath[PATH_MAX];\n        ssize_t len;\n        char *exe;\n\n        if (dent->d_name[0] < '1' || '9' < dent->d_name[0]) {\n            continue;\n        }\n        sprintf(path, \"/proc/%s/exe\", dent->d_name);\n        len = readlink(path, exepath, sizeof(exepath) - 1);\n        if (len == -1) {\n            continue;\n        }\n        exepath[len] = '\\0';\n        exe = strrchr(exepath, '/');\n        if (exe != NULL && strcmp(exe + 1, name) == 0) {\n            pid = atoi(dent->d_name);\n            break;\n        }\n    }\n    closedir(dir);\n    return pid;\n}\n#endif\n\n#ifdef _WIN32\n#include <windows.h>\n#include <tlhelp32.h>\n#include \"../util/ya_getopt.h\"\n\n#define INVALID_PID 0\nstatic DWORD find_process(const char *name)\n{\n    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n    DWORD pid = 0;\n    size_t namelen = strlen(name);\n\n    if (hSnapshot != INVALID_HANDLE_VALUE) {\n        PROCESSENTRY32 pe;\n        pe.dwSize = sizeof(pe);\n\n        if (Process32First(hSnapshot, &pe)) {\n            do {\n                if (_strnicmp(pe.szExeFile, name, namelen) == 0) {\n                    if (pe.szExeFile[namelen] == '\\0' || stricmp(pe.szExeFile + namelen, \".exe\") == 0) {\n                        pid = pe.th32ProcessID;\n                        break;\n                    }\n                }\n            } while (Process32Next(hSnapshot, &pe));\n        }\n        CloseHandle(hSnapshot);\n    }\n    return pid;\n}\n\n#endif\n#ifdef __APPLE__\n#define INVALID_PID -1\n#import <sys/sysctl.h>\n#include \"../util/ya_getopt.h\"\nstatic pid_t find_process(const char *name)\n{\n\tpid_t pid = -1;\n    int max_arg_size = 0;\n\tsize_t size = sizeof(max_arg_size);\n\tif (sysctl((int[]){ CTL_KERN, KERN_ARGMAX }, 2, &max_arg_size, &size, NULL, 0) != 0) {\n\t\tmax_arg_size = 4096; \n\t}\n\t\n\tint mib[3] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL};\n\tstruct kinfo_proc *processes = NULL;\n\tchar* buffer = NULL;\n\tsize_t length;\n\tint count;\n\n\tif (sysctl(mib, 3, NULL, &length, NULL, 0) < 0){\n\t\tgoto clean;\n\t}\n\tprocesses = malloc(length);\n\tif (processes == NULL){\n\t\tgoto clean;\n\t}\n\tif (sysctl(mib, 3, processes, &length, NULL, 0) < 0) {\n\t\tgoto clean;\n\t}\n\tcount = length / sizeof(struct kinfo_proc);\n\tmib[0] = CTL_KERN;\n\tmib[1] = KERN_PROCARGS2;\n\t\n\tbuffer = (char *)malloc(max_arg_size);\n\tfor (int i = 0; i < count; i++) {\n\t\tpid_t p_pid = processes[i].kp_proc.p_pid;\n\t\tif (pid == 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tmib[2] = p_pid;\n\t\tsize = max_arg_size;\n\t\t\n\t\tif (sysctl(mib, 3, buffer, &size, NULL, 0) == 0) {\n\t\t\tchar* exe_path = buffer + sizeof(int);\n\t\t\tchar* exe_name = exe_path;\n\t\t\tchar* next = 0;\n\t\t\tdo{\n\t\t\t\tnext = strchr(exe_name, '/');\n\t\t\t\tif(next != NULL){\n\t\t\t\t\texe_name = next + 1;\n\t\t\t\t}\n\t\t\t} while (next != NULL);\n\t\t\tif(strcmp(exe_name, name) == 0){\n\t\t\t\tpid = p_pid;\n\t\t\t\tgoto clean;\n\t\t\t}\n\t\t}\n\t}\nclean:\n\tif(buffer != 0){\n\t\tfree(buffer);\n\t}\n\tif(processes != 0){\n\t\tfree(processes);\n\t}\n\t\n\treturn pid;\n}\n#endif\nint main(int argc, char **argv)\n{\n    injector_pid_t pid = INVALID_PID;\n    injector_t *injector;\n    int opt;\n    int i;\n    char *endptr;\n    int rv = 0;\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\n    const char *optstring = \"n:p:T\";\n    int cloned_thread = 0;\n#else\n    const char *optstring = \"n:p:\";\n#endif\n\n    while ((opt = getopt(argc, argv, optstring)) != -1) {\n        switch (opt) {\n        case 'n':\n            pid = find_process(optarg);\n            if (pid == INVALID_PID) {\n                fprintf(stderr, \"could not find the process: %s\\n\", optarg);\n                return 1;\n            }\n            printf(\"targeting process \\\"%s\\\" with pid %d\\n\", optarg, pid);\n            break;\n        case 'p':\n            pid = strtol(optarg, &endptr, 10);\n            if (pid <= 0 || *endptr != '\\0') {\n                fprintf(stderr, \"invalid process id number: %s\\n\", optarg);\n                return 1;\n            }\n            printf(\"targeting process with pid %d\\n\", pid);\n            break;\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\n        case 'T':\n            cloned_thread = 1;\n            break;\n#endif\n        }\n    }\n    if (pid == INVALID_PID) {\n        fprintf(stderr, \"Usage: %s [-n process-name] [-p pid] library-to-inject ...\\n\", argv[0]);\n        return 1;\n    }\n\n    if (injector_attach(&injector, pid) != 0) {\n        printf(\"%s\\n\", injector_error());\n        return 1;\n    }\n    for (i = optind; i < argc; i++) {\n        char *libname = argv[i];\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\n        if (cloned_thread) {\n            if (injector_inject_in_cloned_thread(injector, libname, NULL) == 0) {\n                printf(\"clone thread to inject \\\"%s\\\" was created.\\n\", libname);\n            } else {\n                fprintf(stderr, \"could not create cloned thread \\\"%s\\\"\\n\", libname);\n                fprintf(stderr, \"  %s\\n\", injector_error());\n                rv = 1;\n            }\n            continue;\n        }\n#endif\n        if (injector_inject(injector, libname, NULL) == 0) {\n            printf(\"\\\"%s\\\" successfully injected\\n\", libname);\n        } else {\n            fprintf(stderr, \"could not inject \\\"%s\\\"\\n\", libname);\n            fprintf(stderr, \"  %s\\n\", injector_error());\n            rv = 1;\n        }\n    }\n    injector_detach(injector);\n    return rv;\n}\n"
  },
  {
    "path": "include/injector.h",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2018-2023 Kubo Takehiro <kubo@jiubao.org>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n\n/*!\n * \\file injector.h\n * \\brief Library for injecting a shared library into a Linux, Windows and macOS process\n */\n#ifndef INJECTOR_H\n#define INJECTOR_H\n\n#if defined(_WIN32)\n#include <windows.h>\ntypedef DWORD injector_pid_t;\n#else\n#include <sys/types.h>\n\n/*!\n * \\brief Platform-dependent process id type (\\c pid_t on Unix. \\c DWORD on Windows)\n */\ntypedef pid_t injector_pid_t;\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n#if 0\n}\n#endif\n\n#define INJERR_SUCCESS 0               /* linux, windows, macos */\n#define INJERR_OTHER -1                /* linux, windows, macos */\n#define INJERR_NO_MEMORY -2            /* linux, windows, macos */\n#define INJERR_NO_PROCESS -3           /* linux, windows, macos */\n#define INJERR_NO_LIBRARY -4           /* linux */\n#define INJERR_NO_FUNCTION -4          /* linux */\n#define INJERR_ERROR_IN_TARGET -5      /* linux, windows, macos */\n#define INJERR_FILE_NOT_FOUND -6       /* linux, windows, macos */\n#define INJERR_INVALID_MEMORY_AREA -7  /* linux, macos */\n#define INJERR_PERMISSION -8           /* linux, windows, macos */\n#define INJERR_UNSUPPORTED_TARGET -9   /* linux, windows, macos */\n#define INJERR_INVALID_ELF_FORMAT -10  /* linux */\n#define INJERR_WAIT_TRACEE -11         /* linux */\n#define INJERR_FUNCTION_MISSING -12    /* linux, windows, macos */\n\ntypedef struct injector injector_t;\n\n/*!\n * \\brief Attach to the specified process.\n * \\param[out]  injector the address where the newly created injector handle will be stored\n * \\param[in]   pid      the process id to be attached\n * \\return               zero on success. Otherwise, error code\n */\nint injector_attach(injector_t **injector, injector_pid_t pid);\n\n/*!\n * \\brief Detach from the attached process and destroy the specified handle.\n * \\param[in]   injector the injector handle to destroy\n * \\return               zero on success. Otherwise, error code\n */\nint injector_detach(injector_t *injector);\n\n/*!\n * \\brief Inject the specified shared library into the target process.\n * \\param[in]   injector the injector handle specifying the target process\n * \\param[in]   path     the path name of the shared library\n * \\param[out]  handle   the address where the newly created module handle will be stored\n * \\return               zero on success. Otherwise, error code\n *\n * Note on Linux:\n * This calls functions inside of the target process interrupted by \\c ptrace().\n * If the target process is interrupted while holding a non-reentrant lock and\n * injector calls a function requiring the same lock, the process stops forever.\n * If the lock type is reentrant, the status guarded by the lock may become inconsistent.\n * As far as I checked, \\c dlopen() internally calls \\c malloc() requiring non-reentrant\n * locks. \\c dlopen() also uses a reentrant lock to guard information about loaded files.\n */\nint injector_inject(injector_t *injector, const char *path, void **handle);\n\n/*!\n * \\brief Uninject the shared library specified by \\c handle.\n * \\param[in]   injector the injector handle specifying the target process\n * \\param[in]   handle   the module handle created by \\c injector_inject\n * \\return               zero on success. Otherwise, error code\n * \\remarks This fearute isn't supported for musl-libc processes.\n *     See [Functional differences from glibc](https://wiki.musl-libc.org/functional-differences-from-glibc.html#Unloading_libraries).\n */\nint injector_uninject(injector_t *injector, void *handle);\n\n#if defined(INJECTOR_DOC) || defined(__linux__) || defined(__APPLE__)\n/*!\n * \\brief Call the specified function taking no arguments in the target process (Linux and macOS only)\n * \\param[in]   injector the injector handle specifying the target process\n * \\param[in]   handle   the module handle created by \\c injector_inject or special-handles such as \\c RTLD_DEFAULT\n * \\param[in]   name     the function name\n *\n * The \\c handle and \\c name arguments are passed to \\c dlsym ([Linux](https://man7.org/linux/man-pages/man3/dlvsym.3.html), [macOS](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/dlsym.3.html)) and then the return value of \\c dlsym is called without arguments in the target process.\n *\n * This is same with the combination of injector_remote_func_addr() and injector_remote_call() without extra arguments.\n *\n * \\note\n *   (Linux only)\n *   If the function in the target process internally calls non-[async-signal-safe]((https://man7.org/linux/man-pages/man7/signal-safety.7.html))\n *   functions, it may stop the target process or cause unexpected behaviour.\n * \\sa injector_remote_func_addr(), injector_remote_call(), injector_remote_vcall()\n */\nint injector_call(injector_t *injector, void *handle, const char* name);\n#endif\n\n/*!\n * \\brief Get the message of the last error.\n * \\remarks The message is updated only when \\c injector functions return non-zero.\n */\nconst char *injector_error(void);\n\n#if defined(INJECTOR_DOC) || defined(__linux__) || defined(_WIN32)\n#define INJECTOR_HAS_REMOTE_CALL_FUNCS 1\n#include <stdarg.h>\n#include <stdint.h>\n\n/*!\n * \\brief Get the function address in the target process (Linux and Windows only)\n * \\param[in]   injector      the injector handle specifying the target process\n * \\param[in]   handle        the module handle created by \\c injector_inject or special-handles such as \\c RTLD_DEFAULT\n * \\param[in]   name          the function name\n * \\param[out]  func_addr_out the address where the function address in the target process will be stored\n * \\return                    zero on success. Otherwise, error code\n *\n * \\b Example\n *\n * Inject libfoo.so and then call foo_func(1, 2, 3) in it.\n * \\code\n * void *handle;\n * // inject libfoo.so and get the handle\n * if (injector_inject(injector, \"libfoo.so\", &handle) != 0) {\n *    return;\n * }\n * size_t func_addr;\n * // get the address of foo_func in the handle\n * if (injector_remote_func_addr(injector, handle, \"foo_func\", &func_addr) != 0) {\n *    return;\n * }\n * intptr_t retval;\n * // call foo_func\n * if (injector_remote_call(injector, &retval, func_addr, 1, 2, 3) != 0) {\n *    return;\n * }\n * printf(\"The return value of foo_func(1, 2, 3) is %ld.\\n\", retval);\n * \\endcode\n */\nint injector_remote_func_addr(injector_t *injector, void *handle, const char* name, size_t *func_addr_out);\n\n/*!\n * \\brief Call the function in the target process (Linux and Windows only)\n * \\param[in]   injector  the injector handle specifying the target process\n * \\param[out]  retval    \\c NULL or the address where the return value of the function call will be stored\n * \\param[in]   func_addr the function address in the target process\n * \\param[in]   ...       arguments passed to the function\n * \\return                zero on success. Otherwise, error code\n * \\remarks\n *   The types of the arguments must be integer or pointer.\n *   If it is a pointer, it must point to a valid address in the target process.\n *   The number of arguments must be less than or equal to six.\n * \\note\n *   If the function in the target process internally calls non-[async-signal-safe]((https://man7.org/linux/man-pages/man7/signal-safety.7.html))\n *   functions, it may stop the target process or cause unexpected behaviour.\n * \\sa injector_remote_func_addr(), injector_remote_vcall()\n */\nint injector_remote_call(injector_t *injector, intptr_t *retval, size_t func_addr, ...);\n\n/*!\n * \\brief Call the function in the target process (Linux and Windows only)\n * \\param[in]   injector  the injector handle specifying the target process\n * \\param[out]  retval    \\c NULL or the address where the return value of the function call will be stored\n * \\param[in]   func_addr the function address in the target process\n * \\param[in]   ap        arguments passed to the function\n * \\return                zero on success. Otherwise, error code\n * \\remarks\n *   The types of the arguments must be integer or pointer.\n *   If it is a pointer, it must point to a valid address in the target process.\n *   The number of arguments must be less than or equal to six.\n * \\note\n *   If the function in the target process internally calls non-[async-signal-safe]((https://man7.org/linux/man-pages/man7/signal-safety.7.html))\n *   functions, it may stop the target process or cause unexpected behaviour.\n * \\sa injector_remote_func_addr(), injector_remote_call()\n */\nint injector_remote_vcall(injector_t *injector, intptr_t *retval, size_t func_addr, va_list ap);\n#endif\n\n#if defined(INJECTOR_DOC) || defined(_WIN32)\n/*!\n * \\brief Same with \\c injector_inject except the type of the \\c path argument. (Windows only)\n * \\param[in]   injector the injector handle specifying the target process\n * \\param[in]   path     the path name of the shared library\n * \\param[out]  handle   the address where the newly created module handle will be stored\n * \\return               zero on success. Otherwise, error code\n */\nint injector_inject_w(injector_t *injector, const wchar_t *path, void **handle);\n#endif\n\n#if defined(INJECTOR_DOC) || (defined(__linux__) && defined(__x86_64__))\n#define INJECTOR_HAS_INJECT_IN_CLONED_THREAD 1 // feature test macro\n/*!\n * \\brief Inject the specified shared library into the target process by the \\c clone system call. (Linux x86_64 only)\n * \\param[in]   injector the injector handle specifying the target process\n * \\param[in]   path     the path name of the shared library\n * \\param[out]  handle   the address where the newly created module handle will be stored\n * \\return               zero on success. Otherwise, error code\n *\n * This calls `dlopen()` in a thread created by \\c [clone()](https://man7.org/linux/man-pages/man2/clone.2.html). Note that no wonder there are unexpected\n * pitfalls because some resources allocated in \\c [pthread_create()](https://man7.org/linux/man-pages/man3/pthread_create.3.html) lack in the \\c clone()-ed thread.\n * Use it at your own risk.\n */\nint injector_inject_in_cloned_thread(injector_t *injector, const char *path, void **handle);\n#endif\n\n#if 0\n{\n#endif\n#ifdef __cplusplus\n}; /* extern \"C\" */\n#endif\n\n#endif\n"
  },
  {
    "path": "src/linux/Makefile",
    "content": "INJECTOR_OBJS = elf.o injector.o ptrace.o remote_call.o util.o shellcode.o\nCFLAGS = -Wall -fPIC -I../../include\n\nall: libinjector.so libinjector.a\n\nlibinjector.so: $(INJECTOR_OBJS)\n\t$(CC) -shared -o libinjector.so $(INJECTOR_OBJS)\n\nlibinjector.a: $(INJECTOR_OBJS)\n\t$(AR) rcs libinjector.a $(INJECTOR_OBJS)\n\nelf.o: elf.c injector_internal.h ../../include/injector.h\ninjector.o: injector.c injector_internal.h ../../include/injector.h\nptrace.o: ptrace.c injector_internal.h ../../include/injector.h\nremote_call.o: remote_call.c injector_internal.h ../../include/injector.h\nutil.o: util.c injector_internal.h ../../include/injector.h\nshellcode.o: shellcode.S\n\nclean:\n\t$(RM) libinjector.so libinjector.a $(INJECTOR_OBJS)\n"
  },
  {
    "path": "src/linux/elf.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2018 Kubo Takehiro <kubo@jiubao.org>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include <stdio.h>\n#include <stdlib.h>\n#include <inttypes.h>\n#include <regex.h>\n#include <elf.h>\n#include <glob.h>\n#include <sys/sysmacros.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <sys/statfs.h>\n#include <limits.h>\n#include <unistd.h>\n#include \"injector_internal.h\"\n\n#ifdef __LP64__\n#define Elf_Ehdr Elf64_Ehdr\n#define Elf_Shdr Elf64_Shdr\n#define Elf_Sym Elf64_Sym\n#else\n#define Elf_Ehdr Elf32_Ehdr\n#define Elf_Shdr Elf32_Shdr\n#define Elf_Sym Elf32_Sym\n#endif\n\n// #define INJECTOR_DEBUG_ELF_C 1\n\n#ifdef INJECTOR_DEBUG_ELF_C\n#undef DEBUG\n#define DEBUG(...) fprintf(stderr, __VA_ARGS__)\n#else\n#undef DEBUG\n#define DEBUG(...) do {} while(0)\n#endif\n\ntypedef struct {\n    int dlfunc_type; /* -1, DLFUNC_POSIX or DLFUNC_INTERNAL */\n    FILE *fp;\n    size_t libc_addr;\n    size_t str_offset;\n    size_t str_size;\n    size_t sym_offset;\n    size_t sym_num;\n    size_t sym_entsize;\n} param_t;\n\nstatic int search_and_open_libc(FILE **fp_out, pid_t pid, size_t *addr, libc_type_t *libc_type);\nstatic int open_libc(FILE **fp_out, const char *path, pid_t pid, dev_t dev, ino_t ino);\nstatic FILE *fopen_with_ino(const char *path, dev_t dev, ino_t ino);\nstatic int read_elf_ehdr(FILE *fp, Elf_Ehdr *ehdr);\nstatic int read_elf_shdr(FILE *fp, Elf_Shdr *shdr, size_t shdr_size);\nstatic int read_elf_sym(FILE *fp, Elf_Sym *sym, size_t sym_size);\nstatic int find_symbol_addr(size_t *addr, param_t *prm, const char *posix_name, const char *internal_name);\nstatic size_t find_strtab_offset(const param_t *prm, const char *name);\n\nint injector__collect_libc_information(injector_t *injector)\n{\n    pid_t pid = injector->pid;\n    FILE *fp;\n    Elf_Ehdr ehdr;\n    Elf_Shdr shdr;\n    param_t prm = {-1, };\n    size_t shstrtab_offset;\n    int idx;\n    int rv;\n\n    rv = search_and_open_libc(&fp, pid, &prm.libc_addr, &injector->libc_type);\n    if (rv != 0) {\n        return rv;\n    }\n    rv = read_elf_ehdr(fp, &ehdr);\n    if (rv != 0) {\n        goto cleanup;\n    }\n    fseek(fp, ehdr.e_shoff + ehdr.e_shstrndx * ehdr.e_shentsize, SEEK_SET);\n    rv = read_elf_shdr(fp, &shdr, ehdr.e_shentsize);\n    if (rv != 0) {\n        goto cleanup;\n    }\n    shstrtab_offset = shdr.sh_offset;\n\n    fseek(fp, ehdr.e_shoff, SEEK_SET);\n    for (idx = 0; idx < ehdr.e_shnum; idx++) {\n        fpos_t pos;\n        char buf[8];\n\n        rv = read_elf_shdr(fp, &shdr, ehdr.e_shentsize);\n        if (rv != 0) {\n            goto cleanup;\n        }\n        switch (shdr.sh_type) {\n        case SHT_STRTAB:\n            fgetpos(fp, &pos);\n            fseek(fp, shstrtab_offset + shdr.sh_name, SEEK_SET);\n            fgets(buf, sizeof(buf), fp);\n            fsetpos(fp, &pos);\n            if (strcmp(buf, \".dynstr\") == 0) {\n                prm.str_offset = shdr.sh_offset;\n                prm.str_size = shdr.sh_size;\n            }\n            break;\n        case SHT_DYNSYM:\n            fgetpos(fp, &pos);\n            fseek(fp, shstrtab_offset + shdr.sh_name, SEEK_SET);\n            fgets(buf, sizeof(buf), fp);\n            fsetpos(fp, &pos);\n            if (strcmp(buf, \".dynsym\") == 0) {\n                prm.sym_offset = shdr.sh_offset;\n                prm.sym_entsize = shdr.sh_entsize;\n                prm.sym_num = shdr.sh_size / shdr.sh_entsize;\n            }\n            break;\n        }\n        if (prm.sym_offset != 0 && prm.str_offset != 0) {\n            break;\n        }\n    }\n    if (idx == ehdr.e_shnum) {\n        injector__set_errmsg(\"failed to find the .dynstr and .dynsym sections.\");\n        rv = INJERR_INVALID_ELF_FORMAT;\n        goto cleanup;\n    }\n\n    prm.fp = fp;\n\n    rv = find_symbol_addr(&injector->dlopen_addr, &prm, \"dlopen\", \"__libc_dlopen_mode\");\n    if (rv != 0) {\n        goto cleanup;\n    }\n\n    rv = find_symbol_addr(&injector->dlclose_addr, &prm, \"dlclose\", \"__libc_dlclose\");\n    if (rv != 0) {\n        goto cleanup;\n    }\n\n    rv = find_symbol_addr(&injector->dlsym_addr, &prm, \"dlsym\", \"__libc_dlsym\");\n    if (rv != 0) {\n        goto cleanup;\n    }\n\n    if (prm.dlfunc_type != DLFUNC_INTERNAL) {\n        rv = find_symbol_addr(&injector->dlerror_addr, &prm, \"dlerror\", NULL);\n        if (rv != 0) {\n            goto cleanup;\n        }\n    } else {\n        injector->dlerror_addr = 0;\n    }\n\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\n    rv = find_symbol_addr(&injector->clone_addr, &prm, \"clone\", \"clone\");\n    if (rv != 0) {\n        goto cleanup;\n    }\n#endif\n\n    rv = find_symbol_addr(NULL, &prm, \"gnu_get_libc_release\", \"gnu_get_libc_release\");\n    if (rv == 0) {\n        /* GNU libc */\n        injector->libc_type = LIBC_TYPE_GNU;\n    }\n\n    injector->dlfunc_type = prm.dlfunc_type;\n    injector->code_addr = prm.libc_addr + ehdr.e_entry;\n\n    switch (ehdr.e_machine) {\n    case EM_X86_64:\n        if (ehdr.e_ident[EI_CLASS] == ELFCLASS64) {\n            /* LP64 */\n            injector->arch = ARCH_X86_64;\n            injector->sys_mmap = 9;\n            injector->sys_mprotect = 10;\n            injector->sys_munmap = 11;\n        } else {\n            /* ILP32 */\n            injector->arch = ARCH_X86_64_X32;\n            injector->sys_mmap = 0x40000000 + 9;\n            injector->sys_mprotect = 0x40000000 + 10;\n            injector->sys_munmap = 0x40000000 + 11;\n        }\n        break;\n    case EM_386:\n        injector->arch = ARCH_I386;\n        injector->sys_mmap = 192;\n        injector->sys_mprotect = 125;\n        injector->sys_munmap = 91;\n        break;\n    case EM_AARCH64:\n        injector->arch = ARCH_ARM64;\n        injector->sys_mmap = 222;\n        injector->sys_mprotect = 226;\n        injector->sys_munmap = 215;\n        break;\n    case EM_ARM:\n        if (EF_ARM_EABI_VERSION(ehdr.e_flags) == 0) {\n            injector__set_errmsg(\"ARM OABI target process isn't supported.\");\n            rv = INJERR_UNSUPPORTED_TARGET;\n            goto cleanup;\n        }\n        if (injector->code_addr & 1u) {\n            injector->code_addr &= ~1u;\n            injector->arch = ARCH_ARM_EABI_THUMB;\n        } else {\n            injector->arch = ARCH_ARM_EABI;\n        }\n        injector->sys_mmap = 192;\n        injector->sys_mprotect = 125;\n        injector->sys_munmap = 91;\n        break;\n    case EM_MIPS:\n        if (ehdr.e_ident[EI_CLASS] == ELFCLASS64) {\n            /* MIPS 64 */\n            injector->arch = ARCH_MIPS_64;\n            injector->sys_mmap = 5000 + 9;\n            injector->sys_mprotect = 5000 + 10;\n            injector->sys_munmap = 5000 + 11;\n        } else if (ehdr.e_flags & EF_MIPS_ABI2) {\n            /* MIPS N32 */\n            injector->arch = ARCH_MIPS_N32;\n            injector->sys_mmap = 6000 + 9;\n            injector->sys_mprotect = 6000 + 10;\n            injector->sys_munmap = 6000 + 11;\n        } else {\n            /* MIPS O32 */\n            injector->arch = ARCH_MIPS_O32;\n            injector->sys_mmap = 4000 + 90;\n            injector->sys_mprotect = 4000 + 125;\n            injector->sys_munmap = 4000 + 91;\n        }\n        break;\n    case EM_PPC64:\n        injector->arch = ARCH_POWERPC_64;\n        injector->sys_mmap = 90;\n        injector->sys_mprotect = 125;\n        injector->sys_munmap = 91;\n        break;\n    case EM_PPC:\n        injector->arch = ARCH_POWERPC;\n        injector->sys_mmap = 90;\n        injector->sys_mprotect = 125;\n        injector->sys_munmap = 91;\n        break;\n#ifdef EM_RISCV\n    case EM_RISCV:\n        if (ehdr.e_ident[EI_CLASS] == ELFCLASS64) {\n            injector->arch = ARCH_RISCV_64;\n        } else {\n            injector->arch = ARCH_RISCV_32;\n        }\n        injector->sys_mmap = 222;\n        injector->sys_mprotect = 226;\n        injector->sys_munmap = 215;\n        break;\n#endif\n    default:\n        injector__set_errmsg(\"Unknown target process architecture: 0x%04x\", ehdr.e_machine);\n        rv = INJERR_UNSUPPORTED_TARGET;\n        goto cleanup;\n    }\n    rv = 0;\ncleanup:\n    fclose(fp);\n    return rv;\n}\n\nstatic int search_and_open_libc(FILE **fp_out, pid_t pid, size_t *addr, libc_type_t *libc_type)\n{\n    char buf[512];\n    FILE *fp = NULL;\n    regex_t reg;\n    regmatch_t match;\n\n    sprintf(buf, \"/proc/%d/maps\", pid);\n    fp = fopen(buf, \"r\");\n    if (fp == NULL) {\n        injector__set_errmsg(\"failed to open %s. (error: %s)\", buf, strerror(errno));\n        return INJERR_OTHER;\n    }\n    DEBUG(\"Open %s\\n\", buf);\n    /* /libc.so.6 or /libc-2.{DIGITS}.so or /ld-musl-{arch}.so.1 */\n    if (regcomp(&reg, \"/libc(\\\\.so\\\\.6|-2\\\\.[0-9]+\\\\.so)|/ld-musl-.+?\\\\.so\\\\.1\", REG_EXTENDED) != 0) {\n        injector__set_errmsg(\"regcomp failed!\");\n        return INJERR_OTHER;\n    }\n    while (fgets(buf, sizeof(buf), fp) != NULL) {\n        unsigned long saddr, eaddr;\n        unsigned long long offset, inode;\n        unsigned int dev_major, dev_minor;\n        DEBUG(\"   %s\", buf);\n        if (sscanf(buf, \"%lx-%lx %*s %llx %x:%x %llu\", &saddr, &eaddr, &offset, &dev_major, &dev_minor, &inode) != 6) {\n            continue;\n        }\n        if (offset != 0) {\n            continue;\n        }\n        if (regexec(&reg, buf, 1, &match, 0) != 0) {\n            continue;\n        }\n        char *p = buf + match.rm_eo;\n        if (strcmp(p, \" (deleted)\\n\") == 0) {\n            injector__set_errmsg(\"The C library when the process started was removed\");\n            fclose(fp);\n            regfree(&reg);\n            return INJERR_NO_LIBRARY;\n        }\n        if (strcmp(p, \"\\n\") != 0) {\n            continue;\n        }\n        fclose(fp);\n        *addr = saddr;\n        if (strstr(buf, \"/ld-musl-\") != NULL) {\n            *libc_type = LIBC_TYPE_MUSL;\n        } else {\n            *libc_type = LIBC_TYPE_GNU;\n        }\n        regfree(&reg);\n        *p = '\\0';\n        p = strchr(buf, '/');\n        DEBUG(\" libc in /proc/PID/maps: '%s'\\n\", p);\n        return open_libc(fp_out, p, pid, makedev(dev_major, dev_minor), inode);\n    }\n    fclose(fp);\n    injector__set_errmsg(\"Could not find libc\");\n    regfree(&reg);\n    return INJERR_NO_LIBRARY;\n}\n\nstatic int open_libc(FILE **fp_out, const char *path, pid_t pid, dev_t dev, ino_t ino)\n{\n    FILE *fp = fopen_with_ino(path, dev, ino);\n\n    if (fp != NULL) {\n        goto found;\n    }\n\n    /* workaround for LXD */\n    const char *p = strstr(path, \"/rootfs/\"); \n    if (p != NULL) {\n        fp = fopen_with_ino(p + 7, dev, ino);\n        if (fp != NULL) {\n           goto found;\n        }\n    }\n\n    // workaround for Flatpak (https://flatpak.org/)\n    //\n    // libc is under /proc/<PID>/root.\n    // The idea came from https://github.com/kubo/injector/pull/36.\n    char buf[PATH_MAX];\n    snprintf(buf, sizeof(buf), \"/proc/%d/root%s\", pid, path);\n    buf[sizeof(buf) - 1] = '\\0';\n    fp = fopen_with_ino(buf, dev, ino);\n    if (fp != NULL) {\n        goto found;\n    }\n\n    // workaround for Snap\n    //\n    // libc is in a base snap (https://snapcraft.io/docs/base-snaps),\n    glob_t globbuf;\n    if (glob(\"/snap/core*/*\", GLOB_NOSORT, NULL, &globbuf) == 0) {\n        size_t idx;\n        for (idx = 0; idx < globbuf.gl_pathc; idx++) {\n            char buf[512];\n            snprintf(buf, sizeof(buf), \"%s%s\", globbuf.gl_pathv[idx], path);\n            buf[sizeof(buf) - 1] = '\\0';\n            fp = fopen_with_ino(buf, dev, ino);\n            if (fp != NULL) {\n                globfree(&globbuf);\n                goto found;\n            }\n        }\n        globfree(&globbuf);\n    }\n    injector__set_errmsg(\"failed to open %s. (dev:0x%\" PRIx64 \", ino:%lu)\", path, dev, ino);\n    return INJERR_NO_LIBRARY;\nfound:\n    *fp_out = fp;\n    return 0;\n}\n\nstatic inline int is_on_overlay_fs(int fd)\n{\n    struct statfs sbuf;\n    if (fstatfs(fd, &sbuf) != 0) {\n        DEBUG(\" fstatfs() error %s\\n\", strerror(errno));\n        return -1;\n    }\n#ifndef OVERLAYFS_SUPER_MAGIC\n#define OVERLAYFS_SUPER_MAGIC 0x794c7630\n#endif\n    return (sbuf.f_type == OVERLAYFS_SUPER_MAGIC) ? 1 : 0;\n}\n\nstatic FILE *fopen_with_ino(const char *path, dev_t dev, ino_t ino)\n{\n    DEBUG(\"   checking: '%s' ...\", path);\n    struct stat sbuf;\n    FILE *fp = fopen(path, \"r\");\n\n    if (fp == NULL) {\n        DEBUG(\" fopen() error %s\\n\", strerror(errno));\n        return NULL;\n    }\n\n    if (fstat(fileno(fp), &sbuf) != 0) {\n        DEBUG(\" fstat() error %s\\n\", strerror(errno));\n        goto cleanup;\n    }\n    if (sbuf.st_ino != ino) {\n        DEBUG(\" unexpected inode number: expected %llu but %llu\\n\",\n              (unsigned long long)ino, (unsigned long long)sbuf.st_ino);\n        goto cleanup;\n    }\n    if (sbuf.st_dev != dev) {\n        int rv = is_on_overlay_fs(fileno(fp));\n        if (rv < 0) {\n            goto cleanup;\n        }\n        if (rv != 1) {\n            DEBUG(\" unexpected device number: expected %llu but %llu\\n\",\n                  (unsigned long long)dev, (unsigned long long)sbuf.st_dev);\n            goto cleanup;\n        }\n        DEBUG(\" ignore device number mismatch (expected %llu but %llu) on overlay file system  ... \",\n              (unsigned long long)dev, (unsigned long long)sbuf.st_dev);\n    }\n\n    DEBUG(\" OK\\n\");\n    return fp;\ncleanup:\n    fclose(fp);\n    return NULL;\n}\n\nstatic int read_elf_ehdr(FILE *fp, Elf_Ehdr *ehdr)\n{\n    if (fread(ehdr, sizeof(*ehdr), 1, fp) != 1) {\n        injector__set_errmsg(\"failed to read ELF header. (error: %s)\", strerror(errno));\n        return INJERR_INVALID_ELF_FORMAT;\n    }\n    if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) != 0) {\n        injector__set_errmsg(\"Invalid ELF header: 0x%02x,0x%02x,0x%02x,0x%02x\",\n                           ehdr->e_ident[0], ehdr->e_ident[1], ehdr->e_ident[2], ehdr->e_ident[3]);\n        return INJERR_INVALID_ELF_FORMAT;\n    }\n    switch (ehdr->e_ident[EI_CLASS]) {\n    case ELFCLASS32:\n#ifdef __LP64__\n        {\n            Elf32_Ehdr *ehdr32 = (Elf32_Ehdr *)ehdr;\n            /* copy from last */\n            ehdr->e_shstrndx = ehdr32->e_shstrndx;\n            ehdr->e_shnum = ehdr32->e_shnum;\n            ehdr->e_shentsize = ehdr32->e_shentsize;\n            ehdr->e_phnum = ehdr32->e_phnum;\n            ehdr->e_phentsize = ehdr32->e_phentsize;\n            ehdr->e_ehsize = ehdr32->e_ehsize;\n            ehdr->e_flags = ehdr32->e_flags;\n            ehdr->e_shoff = ehdr32->e_shoff;\n            ehdr->e_phoff = ehdr32->e_phoff;\n            ehdr->e_entry = ehdr32->e_entry;\n            ehdr->e_version = ehdr32->e_version;\n            ehdr->e_machine = ehdr32->e_machine;\n            ehdr->e_type = ehdr32->e_type;\n        }\n#endif\n        break;\n    case ELFCLASS64:\n#ifndef __LP64__\n        injector__set_errmsg(\"64-bit target process isn't supported by 32-bit process.\");\n        return INJERR_UNSUPPORTED_TARGET;\n#endif\n        break;\n    default:\n        injector__set_errmsg(\"Invalid ELF class: 0x%x\", ehdr->e_ident[EI_CLASS]);\n        return INJERR_UNSUPPORTED_TARGET;\n    }\n    return 0;\n}\n\nstatic int read_elf_shdr(FILE *fp, Elf_Shdr *shdr, size_t shdr_size)\n{\n    if (fread(shdr, shdr_size, 1, fp) != 1) {\n        injector__set_errmsg(\"failed to read a section header. (error: %s)\", strerror(errno));\n        return INJERR_INVALID_ELF_FORMAT;\n    }\n#ifdef __LP64__\n    if (shdr_size == sizeof(Elf32_Shdr)) {\n        Elf32_Shdr shdr32 = *(Elf32_Shdr *)shdr;\n        shdr->sh_name = shdr32.sh_name;\n        shdr->sh_type = shdr32.sh_type;\n        shdr->sh_flags = shdr32.sh_flags;\n        shdr->sh_addr = shdr32.sh_addr;\n        shdr->sh_offset = shdr32.sh_offset;\n        shdr->sh_size = shdr32.sh_size;\n        shdr->sh_link = shdr32.sh_link;\n        shdr->sh_info = shdr32.sh_info;\n        shdr->sh_addralign = shdr32.sh_addralign;\n        shdr->sh_entsize = shdr32.sh_entsize;\n    }\n#endif\n    return 0;\n}\n\nstatic int read_elf_sym(FILE *fp, Elf_Sym *sym, size_t sym_size)\n{\n    if (fread(sym, sym_size, 1, fp) != 1) {\n        injector__set_errmsg(\"failed to read a symbol table entry. (error: %s)\", strerror(errno));\n        return INJERR_INVALID_ELF_FORMAT;\n    }\n#ifdef __LP64__\n    if (sym_size == sizeof(Elf32_Sym)) {\n        Elf32_Sym sym32 = *(Elf32_Sym *)sym;\n        sym->st_name = sym32.st_name;\n        sym->st_value = sym32.st_value;\n        sym->st_size = sym32.st_size;\n        sym->st_info = sym32.st_info;\n        sym->st_other = sym32.st_other;\n        sym->st_shndx = sym32.st_shndx;\n    }\n#endif\n    return 0;\n}\n\nstatic int find_symbol_addr(size_t *addr, param_t *prm, const char *posix_name, const char *internal_name)\n{\n    size_t st_name;\n\n    switch (prm->dlfunc_type) {\n    case -1:\n        st_name = find_strtab_offset(prm, posix_name);\n        if (st_name != 0) {\n            prm->dlfunc_type = DLFUNC_POSIX;\n        } else {\n            prm->dlfunc_type = DLFUNC_INTERNAL;\n            st_name = find_strtab_offset(prm, internal_name);\n        }\n        break;\n    case DLFUNC_POSIX:\n        st_name = find_strtab_offset(prm, posix_name);\n        break;\n    case DLFUNC_INTERNAL:\n        st_name = find_strtab_offset(prm, internal_name);\n        break;\n    }\n\n    if (addr == NULL) {\n        return st_name != 0 ? 0 : INJERR_NO_FUNCTION;\n    }\n\n    if (st_name != 0) {\n        Elf_Sym sym;\n        int idx;\n        int rv;\n\n        fseek(prm->fp, prm->sym_offset, SEEK_SET);\n        for (idx = 0; idx < prm->sym_num; idx++) {\n            rv = read_elf_sym(prm->fp, &sym, prm->sym_entsize);\n            if (rv != 0) {\n                return rv;\n            }\n            if (sym.st_name == st_name) {\n                *addr = prm->libc_addr + sym.st_value;\n                return 0;\n            }\n        }\n    }\n    injector__set_errmsg(\"failed to find %s%s%s in the .dynstr section.\",\n                         posix_name, internal_name ? \"/\" : \"\",\n                         internal_name ? internal_name : \"\");\n    return INJERR_NO_FUNCTION;\n}\n\nstatic size_t find_strtab_offset(const param_t *prm, const char *name)\n{\n    size_t off;\n    size_t idx = 0;\n\n    fseek(prm->fp, prm->str_offset, SEEK_SET);\n    for (off = 0; off < prm->str_size; off++) {\n        int c = fgetc(prm->fp);\n        if (c == EOF) {\n            return 0;\n        }\n        if (c == name[idx]) {\n            if (c == 0) {\n                return off - idx;\n            }\n            idx++;\n        } else {\n            idx = 0;\n        }\n    }\n    return 0;\n}\n"
  },
  {
    "path": "src/linux/injector.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2018-2023 Kubo Takehiro <kubo@jiubao.org>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n#include <alloca.h>\n#include <sched.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <errno.h>\n#include <dlfcn.h>\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <sys/mman.h>\n#include <time.h>\n#include <unistd.h>\n#include <limits.h>\n#include \"injector_internal.h\"\n\nstatic inline size_t remote_mem_size(injector_t *injector) {\n    return 2 * injector->data_size + injector->stack_size;\n}\n\nint injector_attach(injector_t **injector_out, pid_t pid)\n{\n    injector_t *injector;\n    int status;\n    intptr_t retval;\n    int prot;\n    int rv = 0;\n\n    injector__errmsg_is_set = 0;\n\n    injector = calloc(1, sizeof(injector_t));\n    if (injector == NULL) {\n        injector__set_errmsg(\"malloc error: %s\", strerror(errno));\n        return INJERR_NO_MEMORY;\n    }\n    injector->pid = pid;\n    rv = injector__attach_process(injector);\n    if (rv != 0) {\n        goto error_exit;\n    }\n    injector->attached = 1;\n\n    do {\n        rv = waitpid(pid, &status, 0);\n    } while (rv == -1 && errno == EINTR);\n    if (rv == -1) {\n        injector__set_errmsg(\"waitpid error while attaching: %s\", strerror(errno));\n        rv = INJERR_WAIT_TRACEE;\n        goto error_exit;\n    }\n\n    rv = injector__collect_libc_information(injector);\n    if (rv != 0) {\n        goto error_exit;\n    }\n    rv = injector__get_regs(injector, &injector->regs);\n    if (rv != 0) {\n        goto error_exit;\n    }\n    rv = injector__read(injector, injector->code_addr, &injector->backup_code, sizeof(injector->backup_code));\n    if (rv != 0) {\n        goto error_exit;\n    }\n\n    injector->data_size = sysconf(_SC_PAGESIZE);\n    injector->stack_size = 2 * 1024 * 1024;\n\n    rv = injector__call_syscall(injector, &retval, injector->sys_mmap, 0,\n                                remote_mem_size(injector), PROT_READ | PROT_WRITE,\n                                MAP_PRIVATE | MAP_ANONYMOUS | MAP_GROWSDOWN, -1, 0);\n    if (rv != 0) {\n        goto error_exit;\n    }\n    if (retval == -1) {\n        injector__set_errmsg(\"mmap error: %s\", strerror(errno));\n        rv = INJERR_ERROR_IN_TARGET;\n        goto error_exit;\n    }\n    injector->mmapped = 1;\n    injector->data = (size_t)retval;\n    injector->stack = (size_t)retval + 2 * injector->data_size;\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\n    injector->shellcode = (size_t)retval + 1 * injector->data_size;\n    prot = PROT_READ | PROT_EXEC;\n#else\n    prot = PROT_NONE;\n#endif\n    rv = injector__call_syscall(injector, &retval, injector->sys_mprotect,\n                                injector->data + injector->data_size, injector->data_size,\n                                prot);\n    if (rv != 0) {\n        goto error_exit;\n    }\n    if (retval != 0) {\n        injector__set_errmsg(\"mprotect error: %s\", strerror(errno));\n        rv = INJERR_ERROR_IN_TARGET;\n        goto error_exit;\n    }\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\n    rv = injector__write(injector, injector->shellcode, &injector_shellcode, injector_shellcode_size);\n    if (rv != 0) {\n        return rv;\n    }\n#endif\n\n    *injector_out = injector;\n    return 0;\nerror_exit:\n    injector_detach(injector);\n    return rv;\n}\n\nint injector_inject(injector_t *injector, const char *path, void **handle)\n{\n    char abspath[PATH_MAX];\n    int dlflags = RTLD_LAZY;\n    size_t len;\n    int rv;\n    intptr_t retval;\n\n    injector__errmsg_is_set = 0;\n\n    if (path[0] == '/') {\n        len = strlen(path) + 1;\n    } else if (realpath(path, abspath) != NULL) {\n        path = abspath;\n        len = strlen(abspath) + 1;\n    } else {\n        injector__set_errmsg(\"failed to get the full path of '%s': %s\",\n                           path, strerror(errno));\n        return INJERR_FILE_NOT_FOUND;\n    }\n\n    if (len > injector->data_size) {\n        injector__set_errmsg(\"too long file path: %s\", path);\n        return INJERR_FILE_NOT_FOUND;\n    }\n\n    rv = injector__write(injector, injector->data, path, len);\n    if (rv != 0) {\n        return rv;\n    }\n    if (injector->dlfunc_type == DLFUNC_INTERNAL) {\n#define __RTLD_DLOPEN\t0x80000000 // glibc internal flag\n        dlflags |= __RTLD_DLOPEN;\n    }\n    rv = injector__call_function(injector, &retval, injector->dlopen_addr, injector->data, dlflags);\n    if (rv != 0) {\n        return rv;\n    }\n    if (retval == 0) {\n        char buf[256 + 1] = {0,};\n        if (injector->dlerror_addr != 0) {\n            rv = injector__call_function(injector, &retval, injector->dlerror_addr);\n            if (rv == 0 && retval != 0) {\n                injector__read(injector, retval, buf, sizeof(buf) - 1);\n            }\n        }\n        if (buf[0] != '\\0') {\n            injector__set_errmsg(\"dlopen failed: %s\", buf);\n        } else {\n            injector__set_errmsg(\"dlopen failed\");\n        }\n        return INJERR_ERROR_IN_TARGET;\n    }\n    if (handle != NULL) {\n        *handle = (void*)retval;\n    }\n    return 0;\n}\n\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\nint injector_inject_in_cloned_thread(injector_t *injector, const char *path, void **handle_out)\n{\n    void *data;\n    injector_shellcode_arg_t *arg;\n    const size_t file_path_offset = offsetof(injector_shellcode_arg_t, file_path);\n    void * const invalid_handle = (void*)-3;\n    char abspath[PATH_MAX];\n    size_t pathlen;\n    int rv;\n    intptr_t retval;\n\n    injector__errmsg_is_set = 0;\n\n    if (injector->arch != ARCH_X86_64) {\n        injector__set_errmsg(\"injector_inject_in_cloned_thread doesn't support %s.\",\n                             injector__arch2name(injector->arch));\n        return INJERR_UNSUPPORTED_TARGET;\n    }\n\n    if (realpath(path, abspath) == NULL) {\n        injector__set_errmsg(\"failed to get the full path of '%s': %s\",\n                           path, strerror(errno));\n        return INJERR_FILE_NOT_FOUND;\n    }\n    pathlen = strlen(abspath) + 1;\n\n    if (file_path_offset + pathlen > injector->data_size) {\n        injector__set_errmsg(\"too long path name: %s\", path);\n        return INJERR_FILE_NOT_FOUND;\n    }\n\n    data = alloca(injector->data_size);\n    memset(data, 0, injector->data_size);\n    arg = (injector_shellcode_arg_t *)data;\n\n    arg->handle = invalid_handle;\n    arg->dlopen_addr = injector->dlopen_addr;\n    arg->dlerror_addr = injector->dlerror_addr;\n    arg->dlflags = RTLD_LAZY;\n    if (injector->dlfunc_type == DLFUNC_INTERNAL) {\n        arg->dlflags |= __RTLD_DLOPEN;\n    }\n    memcpy(arg->file_path, abspath, pathlen);\n\n    rv = injector__write(injector, injector->data, data, injector->data_size);\n    if (rv != 0) {\n        return rv;\n    }\n    rv = injector__call_function(injector, &retval, injector->clone_addr,\n                                 injector->shellcode, injector->stack + injector->stack_size - 4096,\n                                 //CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID,\n                                 CLONE_VM,\n                                 injector->data);\n    if (rv != 0) {\n        return rv;\n    }\n    if (retval == -1) {\n        injector__set_errmsg(\"clone error: %s\", strerror(errno));\n        return INJERR_ERROR_IN_TARGET;\n    }\n    const struct timespec ts = {0, 100000000}; /* 0.1 second */\n    void *handle;\n    int cnt = 0;\n\nretry:\n    nanosleep(&ts, NULL);\n    rv = injector__read(injector, injector->data, &handle, sizeof(handle));\n    if (rv != 0) {\n        return rv;\n    }\n    if (handle == invalid_handle) {\n        int max_retyr_cnt = 50;\n        if (++cnt <= max_retyr_cnt) {\n            goto retry;\n        }\n        injector__set_errmsg(\"dlopen doesn't return in %d seconds.\", max_retyr_cnt / 10);\n        return INJERR_ERROR_IN_TARGET;\n    }\n    if (handle_out != NULL) {\n        *handle_out = handle;\n    }\n    if (handle == NULL) {\n        arg->file_path[0] = '\\0';\n        injector__read(injector, injector->data, data, injector->data_size);\n        if (arg->file_path[0] != '\\0') {\n            injector__set_errmsg(\"%s\", arg->file_path);\n        } else {\n            injector__set_errmsg(\"dlopen error\");\n        }\n        return INJERR_ERROR_IN_TARGET;\n    }\n    return 0;\n}\n#endif\n\nint injector_remote_func_addr(injector_t *injector, void *handle, const char* name, size_t *func_addr_out)\n{\n    int rv;\n    intptr_t retval;\n    size_t len = strlen(name) + 1;\n\n    injector__errmsg_is_set = 0;\n\n    if (len > injector->data_size) {\n        injector__set_errmsg(\"too long function name: %s\", name);\n        return INJERR_FUNCTION_MISSING;\n    }\n    rv = injector__write(injector, injector->data, name, len);\n    if (rv != 0) {\n        return rv;\n    }\n    rv = injector__call_function(injector, &retval, injector->dlsym_addr, handle, injector->data);\n    if (rv != 0) {\n        return rv;\n    }\n    if (retval == 0) {\n        injector__set_errmsg(\"function not found: %s\", name);\n        return INJERR_FUNCTION_MISSING;\n    }\n    *func_addr_out = (size_t)retval;\n    return 0;\n}\n\nint injector_remote_call(injector_t *injector, intptr_t *retval, size_t func_addr, ...)\n{\n    va_list ap;\n    int rv;\n    injector__errmsg_is_set = 0;\n    va_start(ap, func_addr);\n    rv = injector__call_function_va_list(injector, retval, func_addr, ap);\n    va_end(ap);\n    return rv;\n}\n\nint injector_remote_vcall(injector_t *injector, intptr_t *retval, size_t func_addr, va_list ap)\n{\n    injector__errmsg_is_set = 0;\n    return injector__call_function_va_list(injector, retval, func_addr, ap);\n}\n\nint injector_call(injector_t *injector, void *handle, const char* name)\n{\n    size_t func_addr;\n    int rv = injector_remote_func_addr(injector, handle, name, &func_addr);\n    if (rv != 0) {\n        return rv;\n    }\n    return injector__call_function(injector, NULL, func_addr);\n}\n\nint injector_uninject(injector_t *injector, void *handle)\n{\n    int rv;\n    intptr_t retval;\n\n    injector__errmsg_is_set = 0;\n    if (injector->libc_type == LIBC_TYPE_MUSL) {\n        /* Assume that libc is musl. */\n        injector__set_errmsg(\"Cannot uninject libraries under musl libc. See: https://wiki.musl-libc.org/functional-differences-from-glibc.html#Unloading_libraries\");\n        return INJERR_UNSUPPORTED_TARGET;\n    }\n\n    rv = injector__call_function(injector, &retval, injector->dlclose_addr, handle);\n    if (rv != 0) {\n        return rv;\n    }\n    if (retval != 0) {\n        injector__set_errmsg(\"dlclose failed\");\n        return INJERR_ERROR_IN_TARGET;\n    }\n    return 0;\n}\n\nint injector_detach(injector_t *injector)\n{\n    injector__errmsg_is_set = 0;\n\n    if (injector->mmapped) {\n        injector__call_syscall(injector, NULL, injector->sys_munmap, injector->data, remote_mem_size(injector));\n    }\n    if (injector->attached) {\n        injector__detach_process(injector);\n    }\n    free(injector);\n    return 0;\n}\n\nconst char *injector_error(void)\n{\n    return injector__errmsg;\n}\n"
  },
  {
    "path": "src/linux/injector_internal.h",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2018-2023 Kubo Takehiro <kubo@jiubao.org>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#ifndef INJECTOR_INTERNAL_H\n#define INJECTOR_INTERNAL_H 1\n#include <stdarg.h>\n#include <stdint.h>\n#include <string.h>\n#include <sys/types.h>\n#include <sys/user.h>\n#include <sys/ptrace.h>\n#include <errno.h>\n#include \"injector.h\"\n\n#ifdef __LP64__\n#define SIZE_T_FMT \"l\"\n#else\n#define SIZE_T_FMT \"\"\n#endif\n\n#ifdef __arm__\n#define user_regs_struct user_regs\n#endif\n\n#ifdef __mips__\n#include <asm/ptrace.h>\n#define user_regs_struct pt_regs\n#endif\n\n#ifdef __powerpc__\n#include <asm/ptrace.h>\n#define user_regs_struct pt_regs\n#endif\n\n#ifdef __riscv\n#include <asm/ptrace.h>\n#endif\n\n#define PTRACE_OR_RETURN(request, injector, addr, data) do { \\\n    int rv = injector__ptrace(request, injector->pid, addr, data, #request); \\\n    if (rv != 0) { \\\n        return rv; \\\n    } \\\n} while (0)\n\ntypedef enum {\n    /* use dlopen/dlsym/dlclose (glibc 2.34 or later) */\n    DLFUNC_POSIX,\n    /* use __libc_dlopen_mode/__libc_dlsym/__libc_dlclose\" (glibc 2.33 or earlier) */\n    DLFUNC_INTERNAL,\n} dlfunc_type_t;\n\ntypedef enum {\n    LIBC_TYPE_UNKNOWN = 0,\n    LIBC_TYPE_GNU,\n    LIBC_TYPE_MUSL,\n} libc_type_t;\n\ntypedef enum {\n    ARCH_X86_64,\n    ARCH_X86_64_X32,\n    ARCH_I386,\n    ARCH_ARM64,\n    ARCH_ARM_EABI_THUMB,\n    ARCH_ARM_EABI,\n    ARCH_MIPS_64,\n    ARCH_MIPS_N32,\n    ARCH_MIPS_O32,\n    ARCH_POWERPC_64,\n    ARCH_POWERPC,\n    ARCH_RISCV_64,\n    ARCH_RISCV_32,\n} arch_t;\n\ntypedef union {\n#if defined(__x86_64__) || defined(__i386__)\n    uint8_t u8[sizeof(long)];\n#elif defined(__aarch64__) || defined(__arm__)\n    uint16_t u16[4];\n    uint32_t u32[2];\n#elif defined(__mips__)\n    uint32_t u32[4];\n#elif defined(__powerpc__)\n    uint32_t u32[2];\n#elif defined(__riscv)\n    uint32_t u32[2];\n#endif\n    long dummy;\n} code_t;\n\nstruct injector {\n    pid_t pid;\n    uint8_t attached;\n    uint8_t mmapped;\n    arch_t arch;\n    libc_type_t libc_type;\n    struct user_regs_struct regs;\n    dlfunc_type_t dlfunc_type;\n    size_t dlopen_addr;\n    size_t dlclose_addr;\n    size_t dlsym_addr;\n    size_t dlerror_addr;\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\n    size_t clone_addr;\n#endif\n    size_t code_addr; /* address where instructions are written */\n    code_t backup_code;\n    long sys_mmap;\n    long sys_mprotect;\n    long sys_munmap;\n\n    /* memory layout allocated in the target process\n     *\n     *  high +----------------------+\n     *       |     stack area       |\n     *       |      size: 2MB       |\n     *       |----------------------|\n     *       |  inaccessible area   |\n     *       |      size: 4096      |\n     *       |----------------------|\n     *       |      data area       |\n     *       |      size: 4096      |\n     *  low  +----------------------+\n     */\n    size_t data; /* read-write region */\n    size_t data_size; /* page size */\n    size_t stack; /* stack area */\n    size_t stack_size; /* 2MB */\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\n    size_t shellcode;\n#endif\n};\n\n/* elf.c */\nint injector__collect_libc_information(injector_t *injector);\n\n/* ptrace.c */\nint injector__ptrace(int request, pid_t pid, long addr, long data, const char *request_name);\nint injector__attach_process(const injector_t *injector);\nint injector__detach_process(const injector_t *injector);\nint injector__get_regs(const injector_t *injector, struct user_regs_struct *regs);\nint injector__set_regs(const injector_t *injector, const struct user_regs_struct *regs);\nint injector__read(const injector_t *injector, size_t addr, void *buf, size_t len);\nint injector__write(const injector_t *injector, size_t addr, const void *buf, size_t len);\nint injector__continue(const injector_t *injector);\n\n/* remote_call.c - call functions and syscalls in the target process */\nint injector__call_syscall(const injector_t *injector, intptr_t *retval, long syscall_number, ...);\nint injector__call_function(const injector_t *injector, intptr_t *retval, long function_addr, ...);\nint injector__call_function_va_list(const injector_t *injector, intptr_t *retval, long function_addr, va_list ap);\n\n/* util.c */\nextern char injector__errmsg[];\nextern char injector__errmsg_is_set;\nvoid injector__set_errmsg(const char *format, ...) __attribute__((format (printf, 1, 2)));\nconst char *injector__arch2name(arch_t arch);\n\n/* shellcode.S */\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\ntypedef struct {\n    void *handle;\n    size_t dlopen_addr;\n    size_t dlerror_addr;\n    int dlflags;\n    char file_path[0]; // dummy size.\n} injector_shellcode_arg_t;\n\nvoid *injector_shellcode(injector_shellcode_arg_t *arg);\nextern int injector_shellcode_size;\n#endif\n\n#endif\n"
  },
  {
    "path": "src/linux/ptrace.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2018 Kubo Takehiro <kubo@jiubao.org>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include \"injector_internal.h\"\n\n#if defined(__aarch64__) || defined(__riscv)\n#define USE_REGSET\n#include <elf.h> /* for NT_PRSTATUS */\n#include <sys/uio.h> /* for struct iovec */\n#endif\n\nstatic int set_ptrace_error(const char *request_name)\n{\n    int err = errno;\n    injector__set_errmsg(\"%s error : %s\", request_name, strerror(errno));\n    switch (err) {\n    case EFAULT:\n        return INJERR_INVALID_MEMORY_AREA;\n    case EPERM:\n        return INJERR_PERMISSION;\n    case ESRCH:\n        return INJERR_NO_PROCESS;\n    }\n    return INJERR_OTHER;\n}\n\nint injector__ptrace(int request, pid_t pid, long addr, long data, const char *request_name)\n{\n    if (ptrace(request, pid, addr, data) != 0) {\n        return set_ptrace_error(request_name);\n    }\n    return 0;\n}\n\nint injector__attach_process(const injector_t *injector)\n{\n    PTRACE_OR_RETURN(PTRACE_ATTACH, injector, 0, 0);\n    return 0;\n}\n\nint injector__detach_process(const injector_t *injector)\n{\n    PTRACE_OR_RETURN(PTRACE_DETACH, injector, 0, 0);\n    return 0;\n}\n\nint injector__get_regs(const injector_t *injector, struct user_regs_struct *regs)\n{\n#ifdef USE_REGSET\n    struct iovec iovec = { regs, sizeof(*regs) };\n    PTRACE_OR_RETURN(PTRACE_GETREGSET, injector, NT_PRSTATUS, (long)&iovec);\n#else\n    PTRACE_OR_RETURN(PTRACE_GETREGS, injector, 0, (long)regs);\n#endif\n    return 0;\n}\n\nint injector__set_regs(const injector_t *injector, const struct user_regs_struct *regs)\n{\n#ifdef USE_REGSET\n    struct iovec iovec = { (void*)regs, sizeof(*regs) };\n    PTRACE_OR_RETURN(PTRACE_SETREGSET, injector, NT_PRSTATUS, (long)&iovec);\n#else\n    PTRACE_OR_RETURN(PTRACE_SETREGS, injector, 0, (long)regs);\n#endif\n    return 0;\n}\n\nint injector__read(const injector_t *injector, size_t addr, void *buf, size_t len)\n{\n    pid_t pid = injector->pid;\n    long word;\n    char *dest = (char *)buf;\n\n    errno = 0;\n    while (len >= sizeof(long)) {\n        word = ptrace(PTRACE_PEEKTEXT, pid, addr, 0);\n        if (word == -1 && errno != 0) {\n            return set_ptrace_error(\"PTRACE_PEEKTEXT\");\n        }\n        *(long*)dest = word;\n        addr += sizeof(long);\n        dest += sizeof(long);\n        len -= sizeof(long);\n    }\n    if (len != 0) {\n        char *src = (char *)&word;\n        word = ptrace(PTRACE_PEEKTEXT, pid, addr, 0);\n        if (word == -1 && errno != 0) {\n            return set_ptrace_error(\"PTRACE_PEEKTEXT\");\n        }\n        while (len--) {\n            *(dest++) = *(src++);\n        }\n    }\n    return 0;\n}\n\nint injector__write(const injector_t *injector, size_t addr, const void *buf, size_t len)\n{\n    pid_t pid = injector->pid;\n    const char *src = (const char *)buf;\n\n    while (len >= sizeof(long)) {\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, addr, *(long*)src);\n        addr += sizeof(long);\n        src += sizeof(long);\n        len -= sizeof(long);\n    }\n    if (len != 0) {\n        long word = ptrace(PTRACE_PEEKTEXT, pid, addr, 0);\n        char *dest = (char*)&word;\n        if (word == -1 && errno != 0) {\n            return set_ptrace_error(\"PTRACE_PEEKTEXT\");\n        }\n        while (len--) {\n            *(dest++) = *(src++);\n        }\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, addr, word);\n    }\n    return 0;\n}\n\nint injector__continue(const injector_t *injector)\n{\n    PTRACE_OR_RETURN(PTRACE_CONT, injector, 0, 0);\n    return 0;\n}\n"
  },
  {
    "path": "src/linux/remote_call.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2018-2023 Kubo Takehiro <kubo@jiubao.org>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#if defined __linux__\n/* Detect musl libc. See https://stackoverflow.com/a/70211227/985524  */\n#define _GNU_SOURCE\n#include <features.h>\n#ifndef __USE_GNU\n#define MUSL_LIBC\n#endif // __USE_GNU\n#endif // __linux__\n\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <stdio.h>\n#include <inttypes.h>\n#include \"injector_internal.h\"\n\n// #define INJECTOR_DEBUG_REMOTE_CALL 1\n\n#ifdef INJECTOR_DEBUG_REMOTE_CALL\n#undef DEBUG\n#define DEBUG(...) fprintf(stderr, __VA_ARGS__)\n#else\n#undef DEBUG\n#define DEBUG(...) do {} while(0)\n#endif\n\n#ifdef __x86_64__\n#define eip rip\n#define ebp rbp\n#define esp rsp\n#define eax rax\n#define ebx rbx\n#define ecx rcx\n#define edx rdx\n#define esi rsi\n#define edi rdi\n#define ebp rbp\n#endif\n\n#if defined(__arm__)\n#define reg32_return reg_return\n#define uregs regs.uregs\n#endif\n\n#define THUMB_MODE_BIT (1u << 5)\n#define BREAKINST_THUMB 0xde01 /* in linux-source-tree/arch/arm/kernel/ptrace.c */\n#define BREAKINST_ARM 0xe7f001f0 /* in linux-source-tree/arch/arm/kernel/ptrace.c */\n#define BREAKINST_ARM64 0xd4200000 /* asm(\"brk #0\") */\n\n#ifdef __mips__\n#define REG_V0 2\n#define REG_A0 4\n#define REG_A1 5\n#define REG_A2 6\n#define REG_A3 7\n#define REG_A4 8\n#define REG_A5 9\n#define REG_T4 12\n#define REG_T9 25\n#define REG_SP 29\n#define REG_FP 30\n#define REG_RA 31\n\nstatic void print_regs(const injector_t *injector, const struct pt_regs *regs)\n{\n    DEBUG(\"  Registers:\\n\");\n    DEBUG(\"    -- at v0 v1: %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\"\\n\",\n          regs->regs[0], regs->regs[1], regs->regs[2], regs->regs[3]);\n    DEBUG(\"    a0 a1 a2 a3: %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\"\\n\",\n          regs->regs[4], regs->regs[5], regs->regs[6], regs->regs[7]);\n    DEBUG(\"    %s: %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\"\\n\",\n          (injector->arch != ARCH_MIPS_O32) ? \"a4 a5 a6 a7\" : \"t0 t1 t2 t3\",\n          regs->regs[8], regs->regs[9], regs->regs[10], regs->regs[11]);\n    DEBUG(\"    t4 t5 t6 t7: %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\"\\n\",\n          regs->regs[12], regs->regs[13], regs->regs[14], regs->regs[15]);\n    DEBUG(\"    s0 s1 s2 s3: %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\"\\n\",\n          regs->regs[16], regs->regs[17], regs->regs[18], regs->regs[19]);\n    DEBUG(\"    s4 s5 s6 s7: %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\"\\n\",\n          regs->regs[20], regs->regs[21], regs->regs[22], regs->regs[23]);\n    DEBUG(\"    t8 t9 k0 k1: %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\"\\n\",\n          regs->regs[24], regs->regs[25], regs->regs[26], regs->regs[27]);\n    DEBUG(\"    gp sp s8 ra: %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\"\\n\",\n          regs->regs[28], regs->regs[29], regs->regs[30], regs->regs[31]);\n    DEBUG(\"    lo hi epc:                    %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\"\\n\",\n          regs->lo, regs->hi, regs->cp0_epc);\n    DEBUG(\"    badvaddr status cause:        %016\"PRIx64\" %016\"PRIx64\" %016\"PRIx64\"\\n\",\n          regs->cp0_badvaddr, regs->cp0_status, regs->cp0_cause);\n}\n#define PRINT_REGS(injector, regs) print_regs((injector), (regs))\n#endif /* __mips__ */\n\n\n#ifdef __powerpc__\nstatic void print_regs(const injector_t *injector, const struct pt_regs *regs)\n{\n#undef WIDTH\n#ifdef __LP64__\n#define WIDTH \"016\"\n#define softe_or_mq_str \"softe\"\n#define softe_or_mq softe\n#else\n#define WIDTH \"08\"\n#define softe_or_mq_str \"mq   \"\n#define softe_or_mq mq\n#endif\n    DEBUG(\"  Registers:\\n\");\n    DEBUG(\"    gpr0  gpr1  gpr2   gpr3   : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->gpr[0], regs->gpr[1], regs->gpr[2], regs->gpr[3]);\n    DEBUG(\"    gpr4  gpr5  gpr6   gpr7   : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->gpr[4], regs->gpr[5], regs->gpr[6], regs->gpr[7]);\n    DEBUG(\"    gpr8  gpr9  gpr10  gpr11  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->gpr[8], regs->gpr[9], regs->gpr[10], regs->gpr[11]);\n    DEBUG(\"    gpr12 gpr13 gpr14  gpr15  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->gpr[12], regs->gpr[13], regs->gpr[14], regs->gpr[15]);\n    DEBUG(\"    gpr16 gpr17 gpr18  gpr19  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->gpr[16], regs->gpr[17], regs->gpr[18], regs->gpr[19]);\n    DEBUG(\"    gpr20 gpr21 gpr22  gpr23  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->gpr[20], regs->gpr[21], regs->gpr[22], regs->gpr[23]);\n    DEBUG(\"    gpr24 gpr25 gpr26  gpr27  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->gpr[24], regs->gpr[25], regs->gpr[26], regs->gpr[27]);\n    DEBUG(\"    gpr28 gpr29 gpr30  gpr31  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->gpr[28], regs->gpr[29], regs->gpr[30], regs->gpr[31]);\n    DEBUG(\"    nip   msr   orig_gpr3 ctr : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->nip, regs->msr, regs->orig_gpr3, regs->ctr);\n    DEBUG(\"    link  xer   ccr    \"softe_or_mq_str\"  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->link, regs->xer, regs->ccr, regs->softe_or_mq);\n    DEBUG(\"    trap  dar   dsisr  result : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->trap, regs->dar, regs->dsisr, regs->result);\n#undef WIDTH\n}\n#define PRINT_REGS(injector, regs) print_regs((injector), (regs))\n#endif\n\n#ifdef __riscv\n#define REG_RA 1\n#define REG_T1 6\n#ifdef __LP64__\n#define WIDTH \"016\"\n#else\n#define WIDTH \"08\"\n#endif\nstatic void print_regs(const injector_t *injector, const struct user_regs_struct *regs)\n{\n    DEBUG(\"  Registers:\\n\");\n    DEBUG(\"    pc  ra  sp  gp  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->pc, regs->ra, regs->sp, regs->gp);\n    DEBUG(\"    tp  t0  t1  t2  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->tp, regs->t0, regs->t1, regs->t2);\n    DEBUG(\"    s0  s1  a0  a1  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->s0, regs->s1, regs->a0, regs->a1);\n    DEBUG(\"    a2  a3  a4  a5  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->a2, regs->a3, regs->a4, regs->a5);\n    DEBUG(\"    a6  a7  s2  s3  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->a6, regs->a7, regs->s2, regs->s3);\n    DEBUG(\"    s4  s5  s6  s7  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->s4, regs->s5, regs->s6, regs->s7);\n    DEBUG(\"    s8  s9  s10 s11 : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->s8, regs->s9, regs->s10, regs->s11);\n    DEBUG(\"    t3  t4  t5  t6  : %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx %\"WIDTH\"lx\\n\",\n          regs->t3, regs->t4, regs->t5, regs->t6);\n}\n#define PRINT_REGS(injector, regs) print_regs((injector), (regs))\n#endif\n\n/* register type used in struct user_regs_struct */\n#if defined(__mips__)\ntypedef uint64_t user_reg_t;\n#elif defined(__riscv)\ntypedef unsigned long user_reg_t;\n#elif defined(__LP64__) && !defined(MUSL_LIBC)\ntypedef unsigned long long user_reg_t;\n#elif defined(__i386__)\ntypedef long user_reg_t;\n#else\ntypedef unsigned long user_reg_t;\n#endif\n\nstatic int kick_then_wait_sigtrap(const injector_t *injector, struct user_regs_struct *regs, code_t *code, size_t code_size);\n\n#ifndef PRINT_REGS\n#define PRINT_REGS(injector, regs) do {} while (0)\n#endif\n\n/*\n * Call the specified system call in the target process.\n *\n * The arguments after syscall_number must be integer types and\n * the size must not be greater than the size of long.\n */\nint injector__call_syscall(const injector_t *injector, intptr_t *retval, long syscall_number, ...)\n{\n    struct user_regs_struct regs = injector->regs;\n    code_t code;\n    size_t code_size;\n    long arg1, arg2, arg3, arg4, arg5, arg6;\n    va_list ap;\n    int rv;\n#if !defined(__mips__) && !defined(__powerpc__)\n    user_reg_t *reg_return = NULL;\n#if defined(__aarch64__)\n    uint32_t *reg32_return = NULL;\n    uint32_t *uregs = (uint32_t *)&regs;\n#endif\n#endif\n\n    va_start(ap, syscall_number);\n    arg1 = va_arg(ap, long);\n    arg2 = va_arg(ap, long);\n    arg3 = va_arg(ap, long);\n    arg4 = va_arg(ap, long);\n    arg5 = va_arg(ap, long);\n    arg6 = va_arg(ap, long);\n    va_end(ap);\n\n    DEBUG(\"injector__call_syscall:\\n\");\n    DEBUG(\"  args: %ld, %lx, %lx, %lx, %lx, %lx, %lx\\n\", syscall_number, arg1, arg2, arg3, arg4, arg5, arg6);\n\n#if !(defined(__x86_64__) && defined(__LP64__))\n    if (injector->arch == ARCH_X86_64_X32) {\n        injector__set_errmsg(\"x32-ABI target process is supported only by x86_64.\");\n        return INJERR_UNSUPPORTED_TARGET;\n    }\n#endif\n\n    switch (injector->arch) {\n#if defined(__x86_64__) && defined(__LP64__)\n    case ARCH_X86_64:\n    case ARCH_X86_64_X32:\n        /* setup instructions */\n        code.u8[0] = 0x0f;\n        code.u8[1] = 0x05; /* 0f 05 : syscall */\n        code.u8[2] = 0xcc; /* cc    : int3    */\n        memset(&code.u8[3], 0x90, sizeof(long) - 3); /* fill the rests with `nop` */\n        code_size = sizeof(long);\n        /* setup registers */\n        regs.rip = injector->code_addr;\n        regs.rax = syscall_number;\n        regs.rdi = arg1;\n        regs.rsi = arg2;\n        regs.rdx = arg3;\n        regs.r10 = arg4;\n        regs.r8 = arg5;\n        regs.r9 = arg6;\n        reg_return = &regs.rax;\n        break;\n#endif\n#if defined(__x86_64__) || defined(__i386__)\n    case ARCH_I386:\n        /* setup instructions */\n        code.u8[0] = 0xcd;\n        code.u8[1] = 0x80; /* cd 80 : int $80 */\n        code.u8[2] = 0xcc; /* cc    : int3    */\n        memset(&code.u8[3], 0x90, sizeof(long) - 3); /* fill the rests with `nop` */\n        code_size = sizeof(long);\n        /* setup registers */\n        regs.eip = injector->code_addr;\n        regs.eax = syscall_number;\n        regs.ebx = arg1;\n        regs.ecx = arg2;\n        regs.edx = arg3;\n        regs.esi = arg4;\n        regs.edi = arg5;\n        regs.ebp = arg6;\n        reg_return = &regs.eax;\n        break;\n#endif\n#if defined(__aarch64__)\n    case ARCH_ARM64:\n        /* setup instructions */\n        code.u32[0] = 0xd4000001; /* svc #0 */\n        code.u32[1] = BREAKINST_ARM64;\n        code_size = 2 * 4;\n        /* setup registers */\n        regs.pc = injector->code_addr;\n        regs.regs[8] = syscall_number;\n        regs.regs[0] = arg1;\n        regs.regs[1] = arg2;\n        regs.regs[2] = arg3;\n        regs.regs[3] = arg4;\n        regs.regs[4] = arg5;\n        regs.regs[5] = arg6;\n        reg_return = &regs.regs[0];\n        break;\n#endif\n#if defined(__aarch64__) || defined(__arm__)\n    case ARCH_ARM_EABI_THUMB:\n        /* setup instructions */\n        code.u16[0] = 0xdf00; /* svc #0 */\n        code.u16[1] = BREAKINST_THUMB;\n#ifdef __LP64__\n        code.u16[2] = 0x46c0; /* nop (mov r8, r8) */\n        code.u16[3] = 0x46c0; /* nop (mov r8, r8) */\n#endif\n        code_size = sizeof(long);\n        /* setup registers */\n        uregs[16] |= THUMB_MODE_BIT;\n        uregs[15] = injector->code_addr;\n        uregs[7] = syscall_number;\n        uregs[0] = arg1;\n        uregs[1] = arg2;\n        uregs[2] = arg3;\n        uregs[3] = arg4;\n        uregs[4] = arg5;\n        uregs[5] = arg6;\n        reg32_return = &uregs[0];\n        break;\n    case ARCH_ARM_EABI:\n        /* setup instructions */\n        code.u32[0] = 0xef000000; /* svc #0 */\n        code.u32[1] = BREAKINST_ARM;\n        code_size = 2 * 4;\n        /* setup registers */\n        uregs[16] &= ~THUMB_MODE_BIT;\n        uregs[15] = injector->code_addr;\n        uregs[7] = syscall_number;\n        uregs[0] = arg1;\n        uregs[1] = arg2;\n        uregs[2] = arg3;\n        uregs[3] = arg4;\n        uregs[4] = arg5;\n        uregs[5] = arg6;\n        reg32_return = &uregs[0];\n        break;\n#endif\n#if defined(__mips__)\n    case ARCH_MIPS_64:\n    case ARCH_MIPS_N32:\n    case ARCH_MIPS_O32:\n        /* setup instructions */\n        if (syscall_number > 0xffff) {\n            injector__set_errmsg(\"too large system call number: %d\", syscall_number);\n            return INJERR_OTHER;\n        }\n        code.u32[0] = 0x00000025 | (REG_A3 << 11) | (REG_T4 << 21); /* or $a3, $t4, $zero; move $a3, $t4 */\n        code.u32[1] = 0x24000000 | (REG_V0 << 16) | syscall_number; /* addiu $v0, $zero, syscall_number */\n        code.u32[2] = 0x0000000c; /* syscall */\n        code.u32[3] = 0x0000000d; /* break */\n        code_size = 4 * 4;\n        DEBUG(\"  Code: %08\"PRIx32\" %08\"PRIx32\" %08\"PRIx32\" %08\"PRIx32\"\\n\",\n              code.u32[0], code.u32[1], code.u32[2], code.u32[3]);\n        /* setup registers */\n        regs.cp0_epc  = injector->code_addr;\n        regs.regs[REG_A0] = arg1;\n        regs.regs[REG_A1] = arg2;\n        regs.regs[REG_A2] = arg3;\n        // Use the combination of \"regs.regs[REG_T4] = arg4\" and \"move $a3, $t4\"\n        // instead of \"regs.regs[REG_A3] = arg4\". I don't know why the latter\n        // doesn't work.\n        regs.regs[REG_T4] = arg4;\n        if (injector->arch != ARCH_MIPS_O32) {\n            /* ARCH_MIPS_64 or ARCH_MIPS_N32 */\n            regs.regs[REG_A4] = arg5;\n            regs.regs[REG_A5] = arg6;\n        } else {\n            /* ARCH_MIPS_O32 */\n            regs.regs[REG_SP] -= 32;\n            PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, regs.regs[REG_SP] + 16, arg5);\n            PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, regs.regs[REG_SP] + 20, arg6);\n        }\n        break;\n#endif\n#if defined(__powerpc__)\n#ifdef __LP64__\n    case ARCH_POWERPC_64:\n#endif\n    case ARCH_POWERPC:\n        /* setup instructions */\n        code.u32[0] = 0x44000002; /* sc */\n        code.u32[1] = 0x7fe00008; /* trap */\n        code_size = 2 * 4;\n        /* setup registers */\n        regs.nip = injector->code_addr;\n        regs.gpr[PT_R0] = syscall_number;\n        regs.gpr[PT_R3] = arg1;\n        regs.gpr[PT_R4] = arg2;\n        regs.gpr[PT_R5] = arg3;\n        regs.gpr[PT_R6] = arg4;\n        regs.gpr[PT_R7] = arg5;\n        regs.gpr[PT_R8] = arg6;\n        break;\n#endif\n#if defined(__riscv)\n#ifdef __LP64__\n    case ARCH_RISCV_64:\n#endif\n    case ARCH_RISCV_32:\n        /* setup instructions */\n        code.u32[0] = 0x00000073; /* ecall */\n        code.u32[1] = 0x00100073; /* ebreak */\n        code_size = 2 * 4;\n        DEBUG(\"  Code: %08\"PRIx32\" %08\"PRIx32\"\\n\",\n              code.u32[0], code.u32[1]);\n        /* setup registers */\n        regs.pc  = injector->code_addr;\n        regs.a0 = arg1;\n        regs.a1 = arg2;\n        regs.a2 = arg3;\n        regs.a3 = arg4;\n        regs.a4 = arg5;\n        regs.a5 = arg6;\n        regs.a7 = syscall_number;\n        reg_return = &regs.a0;\n        break;\n#endif\n    default:\n        injector__set_errmsg(\"Unexpected architecture: %s\", injector__arch2name(injector->arch));\n        return INJERR_UNSUPPORTED_TARGET;\n    }\n\n    PRINT_REGS(injector, &regs);\n    rv = kick_then_wait_sigtrap(injector, &regs, &code, code_size);\n    if (rv != 0) {\n        return rv;\n    }\n    PRINT_REGS(injector, &regs);\n\n    if (retval != NULL) {\n#if defined(__mips__)\n        if (regs.regs[REG_A3] == 0) {\n            *retval = (intptr_t)regs.regs[REG_V0];\n        } else {\n            errno = (int)regs.regs[REG_V0];\n            *retval = -1;\n        }\n#elif defined(__powerpc__)\n        /* https://github.com/strace/strace/blob/v5.19/src/linux/powerpc/get_error.c#L21-L26 */\n        if (regs.ccr & 0x10000000) {\n            errno = (int)regs.gpr[PT_R3];\n            *retval = -1;\n        } else {\n            *retval = (intptr_t)regs.gpr[PT_R3];\n        }\n#else\n#if defined(__aarch64__)\n        if (reg32_return != NULL) {\n            if (*reg32_return <= -4096u) {\n                *retval = (intptr_t)*reg32_return;\n            } else {\n                errno = -((int)*reg32_return);\n                *retval = -1;\n            }\n        } else {\n#endif\n            if ((unsigned long)*reg_return <= -4096ul) {\n                *retval = (intptr_t)*reg_return;\n            } else {\n                errno = -((int)*reg_return);\n                *retval = -1;\n            }\n#if defined(__aarch64__)\n        }\n#endif\n#endif /* defined(__mips__) */\n    }\n    return 0;\n}\n\n/*\n * Call the function at the specified address in the target process.\n *\n * The arguments after function_addr must be integer types and\n * the size must not be greater than the size of long.\n */\nint injector__call_function(const injector_t *injector, intptr_t *retval, long function_addr, ...)\n{\n    va_list ap;\n    int rv;\n    va_start(ap, function_addr);\n    rv = injector__call_function_va_list(injector, retval, function_addr, ap);\n    va_end(ap);\n    return rv;\n}\n\n/*\n * Call the function at the specified address in the target process.\n *\n * The arguments after function_addr must be integer types and\n * the size must not be greater than the size of long.\n */\nint injector__call_function_va_list(const injector_t *injector, intptr_t *retval, long function_addr, va_list ap)\n{\n    struct user_regs_struct regs = injector->regs;\n    code_t code;\n    size_t code_size;\n    long arg1, arg2, arg3, arg4, arg5, arg6;\n    int rv;\n    user_reg_t *reg_return = NULL;\n#if defined(__aarch64__)\n    uint32_t *reg32_return = NULL;\n    uint32_t *uregs = (uint32_t *)&regs;\n#endif\n\n    arg1 = va_arg(ap, long);\n    arg2 = va_arg(ap, long);\n    arg3 = va_arg(ap, long);\n    arg4 = va_arg(ap, long);\n    arg5 = va_arg(ap, long);\n    arg6 = va_arg(ap, long);\n\n    DEBUG(\"injector__call_function:\\n\");\n    DEBUG(\"  args: %lx, %lx, %lx, %lx, %lx, %lx, %lx\\n\", function_addr, arg1, arg2, arg3, arg4, arg5, arg6);\n\n    switch (injector->arch) {\n#if defined(__x86_64__) && defined(__LP64__)\n    case ARCH_X86_64:\n    case ARCH_X86_64_X32:\n        /* setup instructions */\n        code.u8[0] = 0xff;\n        code.u8[1] = 0xd0; /* ff d0 : callq *%rax */\n        code.u8[2] = 0xcc; /* cc    : int3        */\n        memset(&code.u8[3], 0x90, sizeof(long) - 3); /* fill the rests with `nop` */\n        code_size = sizeof(long);\n        /* setup registers */\n        regs.rip = injector->code_addr;\n        regs.rbp = injector->stack + injector->stack_size - 16;\n        /* rsp must be aligned to a 16-byte boundary. */\n        regs.rsp = injector->stack + injector->stack_size - (2 * 16);\n        regs.rax = function_addr;\n        regs.rdi = arg1;\n        regs.rsi = arg2;\n        regs.rdx = arg3;\n        regs.rcx = arg4;\n        regs.r8 = arg5;\n        regs.r9 = arg6;\n        reg_return = &regs.rax;\n        break;\n#endif\n#if defined(__x86_64__) || defined(__i386__)\n    case ARCH_I386:\n        /* setup instructions */\n        code.u8[0] = 0xff;\n        code.u8[1] = 0xd0; /* ff d0 : call *%eax */\n        code.u8[2] = 0xcc; /* cc    : int3       */\n        memset(&code.u8[3], 0x90, sizeof(long) - 3); /* fill the rests with `nop` */\n        code_size = sizeof(long);\n        /* setup registers */\n        regs.eip = injector->code_addr;\n        regs.ebp = injector->stack + injector->stack_size - 16;\n        /* esp should be at 16-byte boundary after call instruction.*/\n        regs.esp = injector->stack + injector->stack_size - (3 * 16) + 4;\n        regs.eax = function_addr;\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, regs.esp + 0, arg1);\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, regs.esp + 4, arg2);\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, regs.esp + 8, arg3);\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, regs.esp + 12, arg4);\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, regs.esp + 16, arg5);\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, regs.esp + 20, arg6);\n        reg_return = &regs.eax;\n        break;\n#endif\n#if defined(__aarch64__)\n    case ARCH_ARM64:\n        /* setup instructions */\n        code.u32[0] = 0xd63f00c0; /* blr x6 */\n        code.u32[1] = BREAKINST_ARM64;\n        code_size = 2 * 4;\n        /* setup registers */\n        regs.pc = injector->code_addr;\n        regs.sp = injector->stack + injector->stack_size - 16;\n        regs.regs[6] = function_addr;\n        regs.regs[0] = arg1;\n        regs.regs[1] = arg2;\n        regs.regs[2] = arg3;\n        regs.regs[3] = arg4;\n        regs.regs[4] = arg5;\n        regs.regs[5] = arg6;\n        reg_return = &regs.regs[0];\n        break;\n#endif\n#if defined(__aarch64__) || defined(__arm__)\n    case ARCH_ARM_EABI_THUMB:\n        /* setup instructions */\n        code.u16[0] = 0x47a0; /* blx r4 */\n        code.u16[1] = BREAKINST_THUMB;\n#ifdef __LP64__\n        code.u16[2] = 0x46c0; /* nop (mov r8, r8) */\n        code.u16[3] = 0x46c0; /* nop (mov r8, r8) */\n#endif\n        code_size = sizeof(long);\n        /* setup registers */\n        uregs[16] |= THUMB_MODE_BIT;\n        uregs[15] = injector->code_addr;\n        uregs[13] = injector->stack + injector->stack_size - 16;\n        uregs[4] = function_addr;\n        uregs[0] = arg1;\n        uregs[1] = arg2;\n        uregs[2] = arg3;\n        uregs[3] = arg4;\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, uregs[13] + 0, arg5);\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, uregs[13] + 4, arg6);\n        reg32_return = &uregs[0];\n        break;\n    case ARCH_ARM_EABI:\n        /* setup instructions */\n        code.u32[0] = 0xe12fff34; /* blx r4 */\n        code.u32[1] = BREAKINST_ARM;\n        code_size = 2 * 4;\n        /* setup registers */\n        uregs[16] &= ~THUMB_MODE_BIT;\n        uregs[15] = injector->code_addr;\n        uregs[13] = injector->stack + injector->stack_size - 16;\n        uregs[4] = function_addr;\n        uregs[0] = arg1;\n        uregs[1] = arg2;\n        uregs[2] = arg3;\n        uregs[3] = arg4;\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, uregs[13] + 0, arg5);\n        PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, uregs[13] + 4, arg6);\n        reg32_return = &uregs[0];\n        break;\n#endif\n#if defined(__mips__)\n    case ARCH_MIPS_64:\n    case ARCH_MIPS_N32:\n    case ARCH_MIPS_O32:\n        /* setup instructions */\n        code.u32[0] = 0x00000009 | (REG_RA << 11) | (REG_T9 << 21); /* jalr $t9;  */\n        code.u32[1] = 0x00000025 | (REG_A3 << 11) | (REG_T4 << 21); /* or $a3, $t4, $zero; in a delay slot */\n        code.u32[2] = 0x0000000d; /* break */\n        code.u32[3] = 0x00000000; /* nop */\n        code_size = 4 * 4;\n        DEBUG(\"  Code: %08\"PRIx32\" %08\"PRIx32\" %08\"PRIx32\" %08\"PRIx32\"\\n\",\n              code.u32[0], code.u32[1], code.u32[2], code.u32[3]);\n        /* setup registers */\n        regs.cp0_epc  = injector->code_addr;\n        regs.regs[REG_FP] = injector->stack + injector->stack_size - 32;\n        regs.regs[REG_SP] = injector->stack + injector->stack_size - 64;\n        regs.regs[REG_T9] = function_addr;\n        regs.regs[REG_A0] = arg1;\n        regs.regs[REG_A1] = arg2;\n        regs.regs[REG_A2] = arg3;\n        regs.regs[REG_T4] = arg4;\n        if (injector->arch != ARCH_MIPS_O32) {\n            /* ARCH_MIPS_64 or ARCH_MIPS_N32 */\n            regs.regs[REG_A4] = arg5;\n            regs.regs[REG_A5] = arg6;\n        } else {\n            /* ARCH_MIPS_O32 */\n            PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, regs.regs[REG_SP] + 16, arg5);\n            PTRACE_OR_RETURN(PTRACE_POKETEXT, injector, regs.regs[REG_SP] + 20, arg6);\n        }\n        reg_return = &regs.regs[REG_V0];\n        break;\n#endif\n#if defined(__powerpc__)\n#ifdef __LP64__\n    case ARCH_POWERPC_64:\n#endif\n    case ARCH_POWERPC:\n        /* setup instructions */\n        code.u32[0] = 0x4e800421; /* bctrl */\n        code.u32[1] = 0x7fe00008; /* trap */\n        code_size = 2 * 4;\n        /* setup registers */\n        regs.nip = injector->code_addr;\n        regs.gpr[PT_R1] = injector->stack + injector->stack_size - 256;\n        regs.ctr = function_addr;\n        regs.gpr[PT_R3] = arg1;\n        regs.gpr[PT_R4] = arg2;\n        regs.gpr[PT_R5] = arg3;\n        regs.gpr[PT_R6] = arg4;\n        regs.gpr[PT_R7] = arg5;\n        regs.gpr[PT_R8] = arg6;\n        regs.gpr[PT_R12] = function_addr;\n        reg_return = &regs.gpr[PT_R3];\n        break;\n#endif\n#if defined(__riscv)\n#ifdef __LP64__\n    case ARCH_RISCV_64:\n#endif\n    case ARCH_RISCV_32:\n        /* setup instructions */\n        code.u32[0] = 0x00000067 | (REG_RA << 7) | (REG_T1 << 15) ; /* jalr t1 */\n        code.u32[1] = 0x00100073; /* ebreak */\n        code_size = 2 * 4;\n        DEBUG(\"  Code: %08\"PRIx32\" %08\"PRIx32\"\\n\",\n              code.u32[0], code.u32[1]);\n        /* setup registers */\n        regs.pc = injector->code_addr;\n        regs.sp = injector->stack + injector->stack_size - 16;\n        regs.t1 = function_addr;\n        regs.a0 = arg1;\n        regs.a1 = arg2;\n        regs.a2 = arg3;\n        regs.a3 = arg4;\n        regs.a4 = arg5;\n        regs.a5 = arg6;\n        reg_return = &regs.a0;\n        break;\n#endif\n    default:\n        injector__set_errmsg(\"Unexpected architecture: %s\", injector__arch2name(injector->arch));\n        return -1;\n    }\n\n    PRINT_REGS(injector, &regs);\n    rv = kick_then_wait_sigtrap(injector, &regs, &code, code_size);\n    if (rv != 0) {\n        return rv;\n    }\n    PRINT_REGS(injector, &regs);\n\n    if (retval != NULL) {\n#if defined(__aarch64__)\n        if (reg32_return != NULL) {\n            *retval = (long)*reg32_return;\n        } else {\n            *retval = (long)*reg_return;\n        }\n#else\n        *retval = (long)*reg_return;\n#endif\n    }\n    return 0;\n}\n\nstatic int kick_then_wait_sigtrap(const injector_t *injector, struct user_regs_struct *regs, code_t *code, size_t code_size)\n{\n    int status;\n    int rv;\n\n    rv = injector__set_regs(injector, regs);\n    if (rv != 0) {\n        return rv;\n    }\n    rv = injector__write(injector, injector->code_addr, code, code_size);\n    if (rv != 0) {\n        injector__set_regs(injector, &injector->regs);\n        return rv;\n    }\n\n    rv = injector__continue(injector);\n    if (rv != 0) {\n        goto cleanup;\n    }\n    while (1) {\n        pid_t pid = waitpid(injector->pid, &status, 0);\n        if (pid == -1) {\n            if (errno == EINTR) {\n                continue;\n            }\n            injector__set_errmsg(\"waitpid error: %s\", strerror(errno));\n            rv = INJERR_WAIT_TRACEE;\n            goto cleanup;\n        }\n        if (WIFSTOPPED(status)) {\n#if defined(PT_GETSIGINFO)\n            siginfo_t si = {0,};\n#endif\n            switch (WSTOPSIG(status)) {\n            case SIGTRAP:\n                goto got_sigtrap;\n            case SIGSTOP:\n                rv = injector__continue(injector);\n                if (rv != 0) {\n                    goto cleanup;\n                }\n                break;\n#if defined(PT_GETSIGINFO)\n            case SIGSYS:\n              PTRACE_OR_RETURN(PT_GETSIGINFO, injector, 0, (long)&si);\n              if (si.si_signo == SIGSYS && si.si_code == 1) {\n                  injector__set_errmsg(\"Got SIGSYS. System call %d at address %p might be blocked by seccomp.\",\n                                       si.si_syscall, (void*)si.si_call_addr);\n                  rv = INJERR_OTHER;\n                  goto cleanup;\n              }\n              // FALL THROUGH */\n#endif\n            default:\n                injector__set_errmsg(\"The target process unexpectedly stopped by signal %d.\", WSTOPSIG(status));\n                rv = INJERR_OTHER;\n                goto cleanup;\n            }\n        } else if (WIFEXITED(status)) {\n            injector__set_errmsg(\"The target process unexpectedly terminated with exit code %d.\", WEXITSTATUS(status));\n            rv = INJERR_OTHER;\n            goto cleanup;\n        } else if (WIFSIGNALED(status)) {\n            injector__set_errmsg(\"The target process unexpectedly terminated by signal %d.\", WTERMSIG(status));\n            rv = INJERR_OTHER;\n            goto cleanup;\n        } else {\n            /* never reach here */\n            injector__set_errmsg(\"Unexpected waitpid status: 0x%x\", status);\n            rv = INJERR_OTHER;\n            goto cleanup;\n        }\n    }\ngot_sigtrap:\n    /* success */\n    rv = injector__get_regs(injector, regs);\ncleanup:\n    injector__set_regs(injector, &injector->regs);\n    injector__write(injector, injector->code_addr, &injector->backup_code, code_size);\n    return rv;\n}\n"
  },
  {
    "path": "src/linux/shellcode.S",
    "content": "#if defined(__x86_64__)\n#define handle_offset 0\n#define dlopen_addr_offset 8\n#define dlerror_addr_offset 16\n#define dlflags_offset 24\n#define file_path_offset 28\n#define page_size 4096\n\t.text\n\t.global\tinjector_shellcode\n\t.hidden\tinjector_shellcode\n\t.type\tinjector_shellcode, @function\n\t// void *injector_shellcode(injector_shellcode_arg_t *arg) {\ninjector_shellcode:\n\t//   // prolog\n\tpushq\t%rbx\n\tmovq\t%rdi, %rbx\n\t//   int dlflags = arg->dlflags;\n\tmovl\tdlflags_offset(%rbx), %esi\n\t//   const char *file_path = arg->file_path;\n\tleaq\tfile_path_offset(%rbx), %rdi\n\t//   void *handle = dlopen(file_path, dlflags);\n\tcall\t*dlopen_addr_offset(%rbx)\n\t//   arg->handle = handle;\n\tmovq\t%rax, handle_offset(%rbx)\n\t//   arg->file_path[0] = '\\0';\n\tmovb\t$0, file_path_offset(%rbx)\n\t//   if (handle != NULL) return;\n\ttest\t%rax, %rax\n\tjnz\t.exit\n\t//   if (arg->dlerror_addr == 0) return;\n\tcmpq\t$0, dlerror_addr_offset(%rbx)\n\tje\t.exit\n\t//   char *errmsg = dlerror();\n\tcall\t*dlerror_addr_offset(%rbx)\n\t//   if (errmsg == NULL) return;\n\ttest\t%rax, %rax\n\tjz\t.exit\n\t//   char *dest = arg->file_path\n\tleaq\tfile_path_offset(%rbx), %rdi\n\t//   char *end = (char*)arg + page_size;\n\tleaq\tpage_size(%rbx), %rcx\n.loop:\n\t//   char c = *(errmsg++);\n\tmovb\t(%rax), %dl\n\taddq\t$1, %rax\n\t//   *(dest++) = c;\n\tmovb\t%dl, (%rdi)\n\taddq\t$1, %rdi\n\t//   if (c == 0) return;\n\ttestb\t%dl, %dl\n\tjz\t.exit\n\t//   if (dest < end) goto loop;\n\tcmpq\t%rdi, %rcx\n\tja\t.loop\n.exit:\n\t//   // epilog\n\tpopq\t%rbx\n\tret\n\t// }\n\t.size\tinjector_shellcode, . - injector_shellcode\n\n\t.balign  4\n\t.global\tinjector_shellcode_size\n\t.hidden\tinjector_shellcode_size\n\t.type\tinjector_shellcode_size, @object\n\t.size\tinjector_shellcode_size, 4\ninjector_shellcode_size:\n\t// distance from injector_shellcode to current.\n\t.int\t. - injector_shellcode\n#endif\n"
  },
  {
    "path": "src/linux/util.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2018 Kubo Takehiro <kubo@jiubao.org>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include <stdio.h>\n#include <stdarg.h>\n#include \"injector_internal.h\"\n\nchar injector__errmsg[512];\nchar injector__errmsg_is_set;\n\nvoid injector__set_errmsg(const char *format, ...)\n{\n    va_list ap;\n    int rv;\n\n    /* prevent the error message from being overwritten. */\n    if (injector__errmsg_is_set) {\n        return;\n    }\n    injector__errmsg_is_set = 1;\n\n    va_start(ap, format);\n    rv = vsnprintf(injector__errmsg, sizeof(injector__errmsg), format, ap);\n    va_end(ap);\n    if (rv == -1 || rv >= sizeof(injector__errmsg)) {\n        injector__errmsg[sizeof(injector__errmsg) - 1] = '\\0';\n    }\n}\n\nconst char *injector__arch2name(arch_t arch)\n{\n    switch (arch) {\n    case ARCH_X86_64:\n        return \"x86_64\";\n    case ARCH_X86_64_X32:\n        return \"x86_64 x32-ABI\";\n    case ARCH_I386:\n        return \"i386\";\n    case ARCH_ARM64:\n        return \"ARM64\";\n    case ARCH_ARM_EABI_THUMB:\n        return \"ARM EABI thumb\";\n    case ARCH_ARM_EABI:\n        return \"ARM EABI\";\n    case ARCH_MIPS_64:\n        return \"MIPS 64\";\n    case ARCH_MIPS_N32:\n        return \"MIPS N32 ABI\";\n    case ARCH_MIPS_O32:\n        return \"MIPS O32 ABI\";\n    case ARCH_POWERPC_64:\n        return \"PowerPC 64-bit\";\n    case ARCH_POWERPC:\n        return \"PowerPC\";\n    case ARCH_RISCV_64:\n        return \"RISC-V 64\";\n    case ARCH_RISCV_32:\n        return \"RISC-V 32\";\n    }\n    return \"?\";\n}\n"
  },
  {
    "path": "src/macos/Makefile",
    "content": "INJECTOR_OBJS = injector.o util.o exc_handler.o mach.o mach_excServer.o ptrace.o remote_call.o\r\nCFLAGS = -Wall -fPIC -I../../include\r\n\r\nall: libinjector.dylib libinjector.a\r\n\r\nlibinjector.dylib: $(INJECTOR_OBJS)\r\n\t$(CC) -shared -o libinjector.dylib $(INJECTOR_OBJS)\r\n\r\nlibinjector.a: $(INJECTOR_OBJS)\r\n\t$(AR) rcs libinjector.a $(INJECTOR_OBJS)\r\n\r\ninjector.o: injector.c injector_internal.h ../../include/injector.h\r\nutil.o: util.c injector_internal.h ../../include/injector.h\r\nexc_handler.o: exc_handler.c injector_internal.h ../../include/injector.h\r\nmach.o: mach.c injector_internal.h ../../include/injector.h\r\nmach_excServer.o: mach_excServer.c mach_exc.h injector_internal.h ../../include/injector.h\r\nptrace.o: ptrace.c injector_internal.h ../../include/injector.h\r\nremote_call.o: remote_call.c mach_exc.h injector_internal.h ../../include/injector.h\r\nclean:\r\n\t$(RM) libinjector.dylib libinjector.a $(INJECTOR_OBJS)"
  },
  {
    "path": "src/macos/exc_handler.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2022 TheOiseth\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include \"injector_internal.h\"\n#include <mach/exception_types.h>\n#include <sys/types.h>\n#include <sys/ptrace.h>\n#include <signal.h>\n#include <stdbool.h>\n#define HANDLE_EXC EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION | EXC_MASK_SOFTWARE | EXC_MASK_BREAKPOINT | EXC_MASK_CRASH | EXC_MASK_CORPSE_NOTIFY\nboolean_t mach_exc_server(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);\nint injector__create_exc_handler(injector_t *injector) {\n\tmach_port_name_t \t\texc_port = 0;\n\tmach_msg_type_number_t\texception_types_count;\n\tint rv;\n\tinjector->exc_port = 0;\n\tinjector->saved_exception_types_count = 0;\n\trv = task_get_exception_ports(injector->remote_task,\n                        EXC_MASK_ALL,\n                        injector->saved_masks,\n                        &exception_types_count,\n                        injector->saved_ports,\n                        injector->saved_behaviors,\n                        injector->saved_flavors);\n\t\t\t\t\t\t\n\tinjector->saved_exception_types_count = exception_types_count;\n\tif(rv != 0){\n\t\tinjector__set_errmsg(\"%s error : %s\", \"EXC_GET_PORTS\", mach_error_string(rv));\n\t\treturn INJERR_OTHER;\n\t}\n \n\trv = mach_port_allocate(mach_task_self(),\n                   MACH_PORT_RIGHT_RECEIVE,\n                   &exc_port);\n \tinjector->exc_port = exc_port;\t\n \tif(rv != 0){\n\t\tinjector__set_errmsg(\"%s error : %s\", \"EXC_PORT_ALLOCATE\", mach_error_string(rv));\n\t\trv = INJERR_OTHER;\n\t\tgoto cleanup;\n\t}\n\trv = mach_port_insert_right(mach_task_self(),\n                       exc_port,\n\t\t\t\t\t\texc_port,\n                       MACH_MSG_TYPE_MAKE_SEND);\n\tif(rv != 0){\n\t\tinjector__set_errmsg(\"%s error : %s\", \"EXC_INSERT_RIGHTS\", mach_error_string(rv));\n\t\trv = INJERR_OTHER;\n\t\tgoto cleanup;\n\t}\n\t\n\trv = task_set_exception_ports(injector->remote_task,\n                         HANDLE_EXC,\n                         exc_port,\n                         EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES,\n                         THREAD_STATE_NONE);\n\tif(rv != 0){\n\t\tinjector__set_errmsg(\"%s error : %s\", \"EXC_SET_PORTS\", mach_error_string(rv));\n\t\trv = INJERR_OTHER;\n\t\tgoto cleanup;\n\t}\n\n\treturn 0;\ncleanup:\n\tinjector__release_exc_handler(injector);\nreturn rv;\t\n}\nint injector__handle_exc(injector_t *injector) {\n\tchar req[128], rpl[128];\n\tmach_msg_header_with_injector *mmhwi;\n\tint rv;\n\n\tmmhwi = (mach_msg_header_with_injector*)req;\n\tmmhwi->injector = injector;\n\trv = mach_msg((mach_msg_header_t *)req, MACH_RCV_MSG, 0, sizeof(req), injector->exc_port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); \n\tif (rv != KERN_SUCCESS) {\n\t\tinjector__set_errmsg(\"%s error : %s\", \"EXC_RECV_MACH_MSG\", mach_error_string(rv));\n\t\treturn INJERR_OTHER;\n\t}\n/* suspend all threads in the process after an exception was received */\n \n\ttask_suspend(injector->remote_task);\n\n\tboolean_t message_parsed_correctly = mach_exc_server((mach_msg_header_t *)req, (mach_msg_header_t *)rpl);\n\tif (! message_parsed_correctly) {\n\t\t \n\t\tsize_t parse_exc = ((mig_reply_error_t *)rpl)->RetCode;\n\t\tif(parse_exc != 0 ){\n\t\t\tinjector__set_errmsg(\"%s error : %s\", \"mach_exc_server\", mach_error_string(parse_exc));\n\t\t}\n\t}\n\ttask_resume(injector->remote_task);\n\tmach_msg_size_t send_sz = ((mach_msg_header_t *)rpl)->msgh_size;\n \n\trv = mach_msg((mach_msg_header_t *)rpl, MACH_SEND_MSG, send_sz, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);\n\tif (rv != KERN_SUCCESS) {\n\t\tinjector__set_errmsg(\"%s error : %s\", \"EXC_SEND_MACH_MSG\", mach_error_string(rv));\n\t\treturn INJERR_OTHER;\n\t}\n\treturn 0;\n}\n\nstatic bool isSIGSTOP(exception_type_t exception_type, mach_exception_data_t codes){\n\treturn exception_type == EXC_SOFTWARE && codes[0] == EXC_SOFT_SIGNAL && codes[1] == SIGSTOP;\n}\n\nkern_return_t catch_mach_exception_raise(\n    mach_port_t exception_port, \n    mach_port_t thread_port,\n    mach_port_t task_port,\n    exception_type_t exception_type,\n    mach_exception_data_t codes,\n    mach_msg_type_number_t num_codes,\n\tinjector_t *injector)\n{\n\tinjector->handle_err = 0;\t\n\tbool bad_exc = true;\n\tint rv;\n\tswitch (injector->handle_action)\n\t{\n\t\tcase STOP_CONTINUE:\n\t\t\tif(isSIGSTOP(exception_type, codes)){\n\t\t\t\tbad_exc = false;\n\t\t\t\tinjector__ptrace_update(injector, thread_port);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase STOP_DETACH:\n\t\t\tif(isSIGSTOP(exception_type, codes)){\n\t\t\t\tbad_exc = false;\n\t\t\t\tinjector__ptrace_detach(injector);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TRAP_GETREGS:\n\t\t\tif(exception_type == EXC_BREAKPOINT){\n\t\t\t\tbad_exc = false;\n#if defined(__arm64__) || defined(__aarch64__)\n\t\t\t\tmach_msg_type_number_t thread_state_count = ARM_THREAD_STATE64_COUNT;\n\t\t\t\tarm_thread_state64_t state;\n\t\t\t\trv = thread_get_state(thread_port, ARM_THREAD_STATE64, (thread_state_t)&state, &thread_state_count);\n\t\t\t\tif (rv == KERN_SUCCESS) {\n\t\t\t\t\tinjector->retval = state.__x[0];\n\t\t\t\t} else {\n\t\t\t\t\tinjector__set_errmsg(\"%s error : %s\", \"GET_THREAD_STATE\", mach_error_string(rv));\n\t\t\t\t\tinjector->handle_err = INJERR_ERROR_IN_TARGET;\n\t\t\t\t}\n#else\n\t\t\t\tmach_msg_type_number_t thread_state_count = x86_THREAD_STATE64_COUNT;\n\t\t\t\tx86_thread_state64_t state;\n\t\t\t\trv = thread_get_state(thread_port, x86_THREAD_STATE64, (thread_state_t)&state, &thread_state_count);\n\t\t\t\tif (rv == KERN_SUCCESS) {\n\t\t\t\t\tinjector->retval = state.__rax;\n\t\t\t\t} else {\n\t\t\t\t\tinjector__set_errmsg(\"%s error : %s\", \"GET_THREAD_STATE\", mach_error_string(rv));\n\t\t\t\t\tinjector->handle_err = INJERR_ERROR_IN_TARGET;\n\t\t\t\t}\n#endif\n\t\t\t\tif (injector->mach_thread != 0){\n\t\t\t\t\trv = thread_terminate(injector->mach_thread);\n\t\t\t\t\tinjector->mach_thread = 0;\n\t\t\t\t}\n\t\t\t\trv = thread_suspend(thread_port);\n\t\t\t\tif(rv != KERN_SUCCESS){\n\t\t\t\t\tinjector__set_errmsg(\"%s error : %s\", \"THREAD_SUSPEND\", mach_error_string(rv));\n\t\t\t\t\tinjector->handle_err = INJERR_ERROR_IN_TARGET;\n\t\t\t\t}\n\t\t\t\t//we don't need to continue since we already called task_resume and mach_msg later\n\t\t\t\t//rv = injector__ptrace_continue(injector);\n\t\t\t\t\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TRAP_SETREGS:\n\t\t\tif(exception_type == EXC_BREAKPOINT){\n\t\t\t\tbad_exc = false;\n\t\t\t\tbool thread_init = false;\n\t\t\t\tif(thread_port != injector->mach_thread){\n\t\t\t\t\tthread_init = injector->remote_thread == 0;\n\t\t\t\t\tinjector->remote_thread = thread_port;\n\t\t\t\t}\n#if defined(__arm64__) || defined(__aarch64__)\n\t\t\t\tmach_msg_type_number_t thread_state_count = ARM_THREAD_STATE64_COUNT;\n\t\t\t\tarm_thread_state64_t state;\n\t\t\t\trv = thread_get_state(thread_port, ARM_THREAD_STATE64, (thread_state_t)&state, &thread_state_count);\n\t\t\t\tif (rv != KERN_SUCCESS) {\n\t\t\t\t\tinjector__set_errmsg(\"%s error : %s\", \"GET_THREAD_STATE\", mach_error_string(rv));\n\t\t\t\t\tinjector->handle_err = INJERR_ERROR_IN_TARGET;\n\t\t\t\t\tgoto exit;\n\t\t\t\t}\n\t\t\t\tif(thread_init){\n\t\t\t\t\tmemcpy(&injector->remote_thread_saved_state, &state, sizeof(state));\n\t\t\t\t\tinjector->state_saved = 1;\n\t\t\t\t}\n\t\t\t\tstate.__x[0] = injector->arg1;\n\t\t\t\tstate.__x[1] = injector->arg2;\n\t\t\t\tstate.__x[2] = injector->arg3;\n\t\t\t\tstate.__x[3] = injector->arg4;\n\t\t\t\tstate.__x[4] = injector->arg5;\n\t\t\t\tstate.__x[5] = injector->arg6;\n\t\t\t\tstate.__x[8] = injector->func_addr;\n\t\t\t\tstate.__sp = injector->stack;\n\t\t\t\tstate.__pc = injector->code2_addr + 4;\n\t\t\t\trv = thread_set_state(thread_port, ARM_THREAD_STATE64, (thread_state_t)&state, ARM_THREAD_STATE64_COUNT);\n\t\t\t\tif (rv != KERN_SUCCESS) {\n\t\t\t\t\tinjector__set_errmsg(\"%s error : %s\", \"SET_THREAD_STATE\", mach_error_string(rv));\n\t\t\t\t\tinjector->handle_err = INJERR_ERROR_IN_TARGET;\n\t\t\t\t}\n#else\t\t\t\n\t\t\t\tmach_msg_type_number_t thread_state_count = x86_THREAD_STATE64_COUNT;\n\t\t\t\tx86_thread_state64_t state;\n\n\t\t\t\trv = thread_get_state(thread_port, x86_THREAD_STATE64, (thread_state_t)&state, &thread_state_count);\n\t\t\t\tif (rv != KERN_SUCCESS) {\n\t\t\t\t\tinjector__set_errmsg(\"%s error : %s\", \"GET_THREAD_STATE\", mach_error_string(rv));\n\t\t\t\t\tinjector->handle_err = INJERR_ERROR_IN_TARGET;\n\t\t\t\t\tgoto exit;\n\t\t\t\t}\n\t\t\t\tif(thread_init){\n\t\t\t\t\tmemcpy(&injector->remote_thread_saved_state, &state, sizeof(state));\n\t\t\t\t\tinjector->state_saved = 1;\n\t\t\t\t}\n\t\t\t\tstate.__rax = injector->func_addr;\n\t\t\t\tstate.__rdi = injector->arg1;\n\t\t\t\tstate.__rsi = injector->arg2;\n\t\t\t\tstate.__rdx = injector->arg3;\n\t\t\t\tstate.__rcx = injector->arg4;\n\t\t\t\tstate.__r8 = injector->arg5;\n\t\t\t\tstate.__r9 = injector->arg6;\n\t\t\t\tstate.__rsp = injector->stack;\n\t\t\t\tstate.__rbp = injector->stack;\t\n\t\t\t\trv = thread_set_state(thread_port, x86_THREAD_STATE64, (thread_state_t)&state, x86_THREAD_STATE64_COUNT);\n\t\t\t\tif (rv != KERN_SUCCESS) {\n\t\t\t\t\tinjector__set_errmsg(\"%s error : %s\", \"SET_THREAD_STATE\", mach_error_string(rv));\n\t\t\t\t\tinjector->handle_err = INJERR_ERROR_IN_TARGET;\n\t\t\t\t}\n#endif\n\t\t\t\t//we don't need to continue since we already called task_resume and mach_msg later\n\t\t\t\t//rv = injector__ptrace_continue(injector);\n\n\t\t\t}\n\t\t\tbreak;\n\t}\n\n\tif(bad_exc){\n\t\tif(exception_type == EXC_SOFTWARE){\n\t\t\tinjector__set_errmsg(\"The target process got an unexpected signal %i.\", codes[1]);\t\t\t\n\t\t} else {\n\t\t\tinjector__set_errmsg(\"Got unhandled exception %i.\", exception_type);\n\t\t}\t\n\t\tinjector->handle_err = INJERR_OTHER;\n\t}\nexit:\n    return KERN_SUCCESS;\n}\n \nkern_return_t catch_mach_exception_raise_state(\n    mach_port_t exception_port, \n    exception_type_t exception,\n    const mach_exception_data_t code, \n    mach_msg_type_number_t codeCnt,\n    int *flavor, \n    const thread_state_t old_state,\n    mach_msg_type_number_t old_stateCnt, \n    thread_state_t new_state,\n    mach_msg_type_number_t *new_stateCnt)\n{\n    return MACH_RCV_INVALID_TYPE;\n}\n \nkern_return_t catch_mach_exception_raise_state_identity(\n    mach_port_t exception_port, \n    mach_port_t thread, \n    mach_port_t task,\n    exception_type_t exception, \n    mach_exception_data_t code,\n    mach_msg_type_number_t codeCnt, \n    int *flavor, \n    thread_state_t old_state,\n    mach_msg_type_number_t old_stateCnt, \n    thread_state_t new_state,\n    mach_msg_type_number_t *new_stateCnt)\n{\n    return MACH_RCV_INVALID_TYPE;\n}\n\nint injector__release_exc_handler(injector_t *injector) {\n\tfor (int i = 0; i < injector->saved_exception_types_count; i++) {\n\t\ttask_set_exception_ports(injector->remote_task, injector->saved_masks[i], injector->saved_ports[i], injector->saved_behaviors[i], injector->saved_flavors[i]);\n\t}\t\n\tinjector->saved_exception_types_count = 0;\n\tif (injector->exc_port != 0){\n\t\tmach_port_deallocate(mach_task_self(), injector->exc_port);\n\t\tinjector->exc_port = 0;\n\t}\n\treturn 0;\n}"
  },
  {
    "path": "src/macos/injector.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2022 TheOiseth\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include \"injector_internal.h\"\n#include <stdlib.h>\n#include <unistd.h>\n#include <dlfcn.h>\n#include <sys/syslimits.h>\n#include <signal.h>\n\n#define STACK_SIZE 2 * 1024 * 1024\n#define CODE_SIZE 512\nint injector_attach(injector_t **injector_out, pid_t pid)\n{\n    injector_t *injector;\n    arch_t self_arch, target_arch;\n    int rv = 0;\n\n    injector__errmsg_is_set = 0;\n\n    injector = calloc(1, sizeof(injector_t));\n    if (injector == NULL) {\n        injector__set_errmsg(\"malloc error: %s\", strerror(errno));\n        return INJERR_NO_MEMORY;\n    }\n    injector->pid = pid;\n\trv = injector__get_process_arch(getpid(), &self_arch);\n\tif (rv != 0) {\n\t    goto error_exit;\n\t}\n\trv = injector__get_process_arch(pid, &target_arch);\n\tif (rv != 0) {\n\t    goto error_exit;\n\t}\n\tarch_t sys_arch = injector__get_system_arch();\n\n\tif(self_arch != ARCH_UNKNOWN && target_arch != ARCH_UNKNOWN){\n\t\tif(self_arch != target_arch){\n\t\t\tinjector__set_errmsg(\"%s target process isn't supported by %s process.\", injector__arch2name(target_arch), injector__arch2name(self_arch));\n\t\t\trv = INJERR_UNSUPPORTED_TARGET;\n\t\t\tgoto error_exit;\n\t\t}\n\t\tif(sys_arch == ARCH_ARM64 && self_arch != ARCH_ARM64){\n\t\t\tinjector__set_errmsg(\"%s target process isn't supported by %s process on ARM64 machine.\", injector__arch2name(target_arch), injector__arch2name(self_arch));\n\t\t\trv = INJERR_UNSUPPORTED_TARGET;\n\t\t\tgoto error_exit;\n\t\t}\n\t}\n\n\trv = injector__task_pid(injector);\n\tif (rv != 0) {\n\t\tgoto error_exit;\n    }\n\tinjector->attached = 1;\n\n\trv = injector__create_exc_handler(injector);\n\t\n\tif (rv != 0) {\n\t\tgoto error_exit;\n    }\n\trv = injector__ptrace_attach(injector);\n\tif(rv != 0){\n\t\treturn rv;\n\t}\n\tinjector->handle_action = STOP_CONTINUE;\n\tinjector->handle_err = 0;\n\tdo{\n\t\tinjector__handle_exc(injector);\n\t} while(injector->handle_err != 0);\n\t\n\tinjector->ptrace_attached = 1;\n\t\t\n\tinjector->text_size = sysconf(_SC_PAGESIZE);\n\tinjector->stack_size = STACK_SIZE;\n\tinjector->code_size = CODE_SIZE;\n\t\n\tsize_t alloc_size = injector->text_size + injector->stack_size;\n\t\n\tmach_vm_address_t addr = (vm_address_t)NULL;\n\trv = injector__allocate(injector, &addr, alloc_size, VM_FLAGS_ANYWHERE);\n\tif (rv != 0) {\n\t\tgoto error_exit;\n    }\n\t\n\tmach_vm_address_t code_addr = (vm_address_t)NULL;\n\trv = injector__allocate(injector, &code_addr, CODE_SIZE, VM_FLAGS_ANYWHERE);\n\tif (rv != 0) {\n\t\tgoto error_exit;\n    }\n\t\n\tinjector->allocated = 1;\n    injector->text = (size_t)addr;\n\tinjector->stack = injector->text + injector->text_size + injector->stack_size / 2;\t\n\tinjector->stack &= 0xFFFFFFFFFFFFFFF0; //alignment\n\tinjector->code_addr = (size_t)code_addr;\n\t\n\trv = injector__protect(injector, addr, alloc_size, FALSE, VM_PROT_READ | VM_PROT_WRITE);\n\tif (rv != 0) {\n\t\tgoto error_exit;\n    }\n\t\n\trv = injector__protect(injector, code_addr, CODE_SIZE, FALSE, VM_PROT_READ | VM_PROT_WRITE);\n\tif (rv != 0) {\n\t\tgoto error_exit;\n    }\n\t*injector_out = injector;\n\treturn 0;\nerror_exit:\n    injector_detach(injector);\n    return rv;\n}\n\nint injector_inject(injector_t *injector, const char *path, void **handle)\n{\n    char abspath[PATH_MAX];\n    int dlflags = RTLD_LAZY;\n    size_t len;\n    int rv;\n\tlong retval;\n\tinjector__errmsg_is_set = 0;\n\tif (realpath(path, abspath) == NULL) {\n        injector__set_errmsg(\"failed to get the full path of '%s': %s\",\n                           path, strerror(errno));\n        return INJERR_FILE_NOT_FOUND;\n    }\n\tlen = strlen(abspath) + 1;\n\t if (len > injector->text_size) {\n        injector__set_errmsg(\"too long file path: %s\", path);\n        return INJERR_FILE_NOT_FOUND;\n    }\n\n    rv = injector__write(injector, injector->text, abspath, len);\n    if (rv != 0) {\n        return rv;\n    }\n\t\n\trv = injector__call_function(injector, &retval, (long)dlopen, injector->text, dlflags);\n    if (rv != 0) {\n        return rv;\n    }\n\tif (retval == 0) {\n        char buf[256 + 1] = {0,};\n        rv = injector__call_function(injector, &retval, (long)dlerror);\n        if (rv == 0 && retval != 0) {\n            injector__read(injector, retval, buf, sizeof(buf) - 1);\n        }\n\t\t\n        if (buf[0] != '\\0') {\n            injector__set_errmsg(\"dlopen failed: %s\", buf);\n        } else {\n            injector__set_errmsg(\"dlopen failed\");\n        }\n\n        return INJERR_ERROR_IN_TARGET;\n    }\n\tif (handle != NULL) {\n        *handle = (void*)retval;\n    }\n\treturn 0;\n}\n\nint injector_call(injector_t *injector, void *handle, const char* name)\n{\n    int rv;\n    long retval;\n    size_t len = strlen(name) + 1;\n\n    injector__errmsg_is_set = 0;\n\n    if (len > injector->text_size) {\n        injector__set_errmsg(\"too long function name: %s\", name);\n        return INJERR_FUNCTION_MISSING;\n    }\n    rv = injector__write(injector, injector->text, name, len);\n    if (rv != 0) {\n        return rv;\n    }\n    rv = injector__call_function(injector, &retval, (long)dlsym, handle, injector->text);\n    if (retval == 0) {\n        injector__set_errmsg(\"function not found: %s\", name);\n        return INJERR_FUNCTION_MISSING;\n    }\n    return injector__call_function(injector, &retval, retval);\n}\n\nint injector_uninject(injector_t *injector, void *handle)\n{\n    int rv;\n    long retval;\n\n    injector__errmsg_is_set = 0;\n\n    rv = injector__call_function(injector, &retval, (long)dlclose, handle);\n    if (rv != 0) {\n        return rv;\n    }\n    if (retval != 0) {\n        injector__set_errmsg(\"dlclose failed\");\n        return INJERR_ERROR_IN_TARGET;\n    }\n    return 0;\n}\n\nint injector_detach(injector_t *injector)\n{\n\tint rv = 0;\n    injector__errmsg_is_set = 0;\n\tif (injector->remote_thread != 0) {\n\t\t//For some reasons on MacOS ARM64 (tested on 12.0.1) thread_terminate() returns unknown error, so let it end by itslef\n\t\tif(injector->state_saved){\n#if defined(__arm64__) || defined(__aarch64__)\n\t\t\tinjector->remote_thread_saved_state.__pc = injector->code2_addr + 12;\n\t\t\trv = thread_set_state(injector->remote_thread, ARM_THREAD_STATE64, (thread_state_t)&injector->remote_thread_saved_state, ARM_THREAD_STATE64_COUNT);\n\t\t\tif (rv != KERN_SUCCESS) {\n\t\t\t\tinjector__set_errmsg(\"%s error : %s\", \"GET_THREAD_STATE\", mach_error_string(rv));\n\t\t\t\trv = INJERR_ERROR_IN_TARGET;\n\t\t\t}\n#else\n\t\t\tinjector->remote_thread_saved_state.__rip = injector->code2_addr + 4;\n\t\t\trv = thread_set_state(injector->remote_thread, x86_THREAD_STATE64, (thread_state_t)&injector->remote_thread_saved_state, x86_THREAD_STATE64_COUNT);\n\t\t\tif (rv != KERN_SUCCESS) {\n\t\t\t\tinjector__set_errmsg(\"%s error : %s\", \"GET_THREAD_STATE\", mach_error_string(rv));\n\t\t\t\trv = INJERR_ERROR_IN_TARGET;\n\t\t\t}\n#endif\n\t\t\trv = thread_resume(injector->remote_thread);\n\t\t\tif(rv != 0){\n\t\t\t\tinjector__set_errmsg(\"Remote thread resume error: %s\\n\", mach_error_string(rv));\n\t\t\t\trv = INJERR_ERROR_IN_TARGET;\n\t\t\t}\n\t\t\t\n\t\t\t//wait thread for end\n#if defined(__arm64__) || defined(__aarch64__)\n\t\t\tthread_state_flavor_t flavor = ARM_THREAD_STATE64;\n#else\n\t\t\tthread_state_flavor_t flavor = x86_THREAD_STATE64;\n#endif\n\t\t\tmach_msg_type_number_t state_count;\n\t\t\tint counter = 0;\n\t\t\twhile(thread_get_state(injector->remote_thread, flavor, (thread_state_t)&injector->remote_thread_saved_state, &state_count) == 0){\n\t\t\t\tcounter++;\n\t\t\t\tusleep(10);\n\t\t\t\tif(counter > 1000){\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\t\n\t}\n\t\n\tif (injector->ptrace_attached) {\n\t\tinjector->handle_action = STOP_DETACH;\n\t\tkill(injector->pid, SIGSTOP);\t\t\n\t\tinjector->handle_err = 0;\n\t\tdo{\n\t\t\tinjector__handle_exc(injector);\n\t\t} while(injector->handle_err != 0);\n\t\tinjector__release_exc_handler(injector);\n\t}\n\t\n    if (injector->allocated) {\n\t\tinjector__deallocate(injector, injector->text, injector->text_size + injector->stack_size);\n\t\tinjector__deallocate(injector, injector->code_addr, injector->code_size);\n    }\n    if (injector->attached) {\n\t\tmach_port_deallocate(mach_task_self(), injector->remote_task);\n    }\n\n    free(injector);\n    return rv;\n}\nconst char *injector_error(void)\n{\n    return injector__errmsg;\n}"
  },
  {
    "path": "src/macos/injector_internal.h",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2022 TheOiseth\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include \"injector.h\"\n#include <stdint.h>\n#include <stdbool.h>\n#include <mach/mach_vm.h>\n#include <mach/mach.h>\n#include <errno.h>\n\ntypedef enum {\n    STOP_CONTINUE,\n\tSTOP_DETACH,\n    TRAP_SETREGS,  \n    TRAP_GETREGS\n} handle_action_t;\n\nstruct injector {\n    pid_t pid;\n\tuint8_t attached;\n\tuint8_t allocated;\n\tuint8_t ptrace_attached;\n\tuint8_t shellcode_writed;\n\ttask_t remote_task;\n    size_t code_addr;\n\tsize_t code2_addr;\n\tsize_t code_size;\n    size_t text;\n    size_t text_size;\n    size_t stack;\n    size_t stack_size;\n\t\n\tthread_act_t mach_thread;\n\tthread_act_t remote_thread;\n#if defined(__arm64__) || defined(__aarch64__)\n\tarm_thread_state64_t remote_thread_saved_state;\n#else\n\tx86_thread_state64_t remote_thread_saved_state;\n#endif\n\tuint8_t state_saved;\n\tlong func_addr;\n\tlong arg1;\n\tlong arg2;\n\tlong arg3;\n\tlong arg4;\n\tlong arg5;\n\tlong arg6;\n\tmach_port_name_t \t\texc_port;\n\texception_mask_t\t\tsaved_masks[EXC_TYPES_COUNT];\n\tmach_port_t\t\t\t\tsaved_ports[EXC_TYPES_COUNT];\n\texception_behavior_t\tsaved_behaviors[EXC_TYPES_COUNT];\n\tthread_state_flavor_t\tsaved_flavors[EXC_TYPES_COUNT];\n\tmach_msg_type_number_t\tsaved_exception_types_count;\n\thandle_action_t handle_action;\n\tlong retval;\n\tint handle_err;\n\t\n};\n\ntypedef struct{\n\tchar stub[120];\n\tinjector_t *injector;\n} mach_msg_header_with_injector;\n\ntypedef enum {\n    ARCH_X86_64,\n    ARCH_I386,\n    ARCH_ARM64,  \n    ARCH_POWERPC_64,\n    ARCH_POWERPC,\n\tARCH_UNKNOWN\n} arch_t;\n\n\n\ntypedef int (*pcfmt_t)(pthread_t* ,pthread_attr_t* ,void *, void*);\n\nint injector__task_pid(injector_t *injector);\nint injector__allocate(const injector_t *injector, mach_vm_address_t *address, mach_vm_size_t size, int flags);\nint injector__deallocate(const injector_t *injector, mach_vm_address_t address, mach_vm_size_t size);\nint injector__protect(const injector_t *injector, mach_vm_address_t address, mach_vm_size_t size, boolean_t set_maximum, vm_prot_t new_protection);\nint injector__write(const injector_t *injector, size_t addr, const void *buf, size_t len);\nint injector__read(const injector_t *injector, size_t addr, void *buf, size_t len);\nint injector__ptrace_attach(const injector_t *injector);\nint injector__ptrace_detach(const injector_t *injector);\nint injector__ptrace_continue(const injector_t *injector);\nint injector__ptrace_update(const injector_t *injector, long thread_port);\n\nint injector__create_exc_handler(injector_t *injector);\nint injector__release_exc_handler(injector_t *injector);\nint injector__handle_exc(injector_t *injector);\n\nint injector__call_function(injector_t *injector, long *retval, long function_addr, ...);\n/* util.c */\nextern char injector__errmsg[];\nextern char injector__errmsg_is_set;\nvoid injector__set_errmsg(const char *format, ...);\nconst char *injector__arch2name(arch_t arch);\nint injector__get_process_arch(pid_t pid, arch_t *arch);\narch_t injector__get_system_arch();"
  },
  {
    "path": "src/macos/mach.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2022 TheOiseth\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include \"injector_internal.h\"\n#include <libproc.h>\n#include <signal.h>\nstatic int set_mach_error(const char *request_name, int err)\n{\n    injector__set_errmsg(\"%s error : %s\", request_name, mach_error_string(err));\n    switch (err) {\n    case KERN_INVALID_ADDRESS:\n        return INJERR_INVALID_MEMORY_AREA;\n    case KERN_NO_ACCESS:\n        return INJERR_PERMISSION;\n    }\n    return INJERR_OTHER;\n}\n\nstatic int set_error(const char *request_name)\n{\n    int err = errno;\n    injector__set_errmsg(\"%s error : %s\", request_name, strerror(errno));\n    switch (err) {\n    case EFAULT:\n        return INJERR_INVALID_MEMORY_AREA;\n    case EPERM:\n        return INJERR_PERMISSION;\n    case ESRCH:\n        return INJERR_NO_PROCESS;\n    }\n    return INJERR_OTHER;\n}\n\nint injector__task_pid(injector_t *injector)\n{\n\tint rv = kill(injector->pid, 0);\n\tif(rv != 0){\n\t\treturn set_error(\"TASK_FOR_PID\");\n\t}\n\ttask_t remote_task;\n    rv = task_for_pid(mach_task_self(), injector->pid, &remote_task);\n\t\n\tif (rv != KERN_SUCCESS) {\n\t\treturn set_mach_error(\"TASK_FOR_PID\", rv);\n\t}\n\tinjector->remote_task = remote_task;\n    return 0;\n}\n\nint injector__allocate(const injector_t *injector, mach_vm_address_t *address, mach_vm_size_t size, int flags)\n{\n\tint rv = mach_vm_allocate(injector->remote_task, address, size, flags);\n    if (rv != KERN_SUCCESS) {\n        return set_mach_error(\"ALLOCATE\", rv);\n    }\n\treturn 0;\n}\n\nint injector__deallocate(const injector_t *injector, mach_vm_address_t address, mach_vm_size_t size){\n\tint rv = mach_vm_deallocate(injector->remote_task, address, size);\n    if (rv != KERN_SUCCESS) {\n        return set_mach_error(\"DEALLOCATE\", rv);\n    }\n\treturn 0;\n}\n\nint injector__protect(const injector_t *injector, mach_vm_address_t address, mach_vm_size_t size, boolean_t set_maximum, vm_prot_t new_protection)\n{\n\tint rv = mach_vm_protect(injector->remote_task, address, size, set_maximum, new_protection);\n    if (rv != KERN_SUCCESS) {\n        return set_mach_error(\"PROTECT\", rv);\n    }\n\treturn 0;\n}\n\nint injector__write(const injector_t *injector, size_t addr, const void *buf, size_t len) {\n\tint rv = mach_vm_write(injector->remote_task, addr, (vm_offset_t)buf, len);\n\tif (rv != KERN_SUCCESS) {\n         return set_mach_error(\"WRITE\", rv);\n    }\n\treturn 0;\n}\nint injector__read(const injector_t *injector, size_t addr, void *buf, size_t len){\n\tmach_vm_size_t readed;\n\tint rv = mach_vm_read_overwrite(injector->remote_task, addr, len, (mach_vm_address_t)buf, &readed);\n\tif (rv != KERN_SUCCESS) {\n         return set_mach_error(\"READ\", rv);\n    }\n\treturn 0;\n}\n\n"
  },
  {
    "path": "src/macos/mach_exc.h",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * this code is generated automatically by mig\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#ifndef\t_mach_exc_user_\n#define\t_mach_exc_user_\n\n/* Module mach_exc */\n\n#include <string.h>\n#include <mach/ndr.h>\n#include <mach/boolean.h>\n#include <mach/kern_return.h>\n#include <mach/notify.h>\n#include <mach/mach_types.h>\n#include <mach/message.h>\n#include <mach/mig_errors.h>\n#include <mach/port.h>\n\t\n/* BEGIN VOUCHER CODE */\n\n#ifndef KERNEL\n#if defined(__has_include)\n#if __has_include(<mach/mig_voucher_support.h>)\n#ifndef USING_VOUCHERS\n#define USING_VOUCHERS\n#endif\n#ifndef __VOUCHER_FORWARD_TYPE_DECLS__\n#define __VOUCHER_FORWARD_TYPE_DECLS__\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\textern boolean_t voucher_mach_msg_set(mach_msg_header_t *msg) __attribute__((weak_import));\n#ifdef __cplusplus\n}\n#endif\n#endif // __VOUCHER_FORWARD_TYPE_DECLS__\n#endif // __has_include(<mach/mach_voucher_types.h>)\n#endif // __has_include\n#endif // !KERNEL\n\t\n/* END VOUCHER CODE */\n\n\t\n/* BEGIN MIG_STRNCPY_ZEROFILL CODE */\n\n#if defined(__has_include)\n#if __has_include(<mach/mig_strncpy_zerofill_support.h>)\n#ifndef USING_MIG_STRNCPY_ZEROFILL\n#define USING_MIG_STRNCPY_ZEROFILL\n#endif\n#ifndef __MIG_STRNCPY_ZEROFILL_FORWARD_TYPE_DECLS__\n#define __MIG_STRNCPY_ZEROFILL_FORWARD_TYPE_DECLS__\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\textern int mig_strncpy_zerofill(char *dest, const char *src, int len) __attribute__((weak_import));\n#ifdef __cplusplus\n}\n#endif\n#endif /* __MIG_STRNCPY_ZEROFILL_FORWARD_TYPE_DECLS__ */\n#endif /* __has_include(<mach/mig_strncpy_zerofill_support.h>) */\n#endif /* __has_include */\n\t\n/* END MIG_STRNCPY_ZEROFILL CODE */\n\n\n#ifdef AUTOTEST\n#ifndef FUNCTION_PTR_T\n#define FUNCTION_PTR_T\ntypedef void (*function_ptr_t)(mach_port_t, char *, mach_msg_type_number_t);\ntypedef struct {\n        char            *name;\n        function_ptr_t  function;\n} function_table_entry;\ntypedef function_table_entry   *function_table_t;\n#endif /* FUNCTION_PTR_T */\n#endif /* AUTOTEST */\n\n#ifndef\tmach_exc_MSG_COUNT\n#define\tmach_exc_MSG_COUNT\t3\n#endif\t/* mach_exc_MSG_COUNT */\n\n#include <mach/std_types.h>\n#include <mach/mig.h>\n#include <mach/mig.h>\n#include <mach/mach_types.h>\n\n#ifdef __BeforeMigUserHeader\n__BeforeMigUserHeader\n#endif /* __BeforeMigUserHeader */\n\n#include <sys/cdefs.h>\n__BEGIN_DECLS\n\n\n/* Routine mach_exception_raise */\n#ifdef\tmig_external\nmig_external\n#else\nextern\n#endif\t/* mig_external */\nkern_return_t mach_exception_raise\n(\n\tmach_port_t exception_port,\n\tmach_port_t thread,\n\tmach_port_t task,\n\texception_type_t exception,\n\tmach_exception_data_t code,\n\tmach_msg_type_number_t codeCnt\n);\n\n/* Routine mach_exception_raise_state */\n#ifdef\tmig_external\nmig_external\n#else\nextern\n#endif\t/* mig_external */\nkern_return_t mach_exception_raise_state\n(\n\tmach_port_t exception_port,\n\texception_type_t exception,\n\tconst mach_exception_data_t code,\n\tmach_msg_type_number_t codeCnt,\n\tint *flavor,\n\tconst thread_state_t old_state,\n\tmach_msg_type_number_t old_stateCnt,\n\tthread_state_t new_state,\n\tmach_msg_type_number_t *new_stateCnt\n);\n\n/* Routine mach_exception_raise_state_identity */\n#ifdef\tmig_external\nmig_external\n#else\nextern\n#endif\t/* mig_external */\nkern_return_t mach_exception_raise_state_identity\n(\n\tmach_port_t exception_port,\n\tmach_port_t thread,\n\tmach_port_t task,\n\texception_type_t exception,\n\tmach_exception_data_t code,\n\tmach_msg_type_number_t codeCnt,\n\tint *flavor,\n\tthread_state_t old_state,\n\tmach_msg_type_number_t old_stateCnt,\n\tthread_state_t new_state,\n\tmach_msg_type_number_t *new_stateCnt\n);\n\n__END_DECLS\n\n/********************** Caution **************************/\n/* The following data types should be used to calculate  */\n/* maximum message sizes only. The actual message may be */\n/* smaller, and the position of the arguments within the */\n/* message layout may vary from what is presented here.  */\n/* For example, if any of the arguments are variable-    */\n/* sized, and less than the maximum is sent, the data    */\n/* will be packed tight in the actual message to reduce  */\n/* the presence of holes.                                */\n/********************** Caution **************************/\n\n/* typedefs for all requests */\n\n#ifndef __Request__mach_exc_subsystem__defined\n#define __Request__mach_exc_subsystem__defined\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\t/* start of the kernel processed data */\n\t\tmach_msg_body_t msgh_body;\n\t\tmach_msg_port_descriptor_t thread;\n\t\tmach_msg_port_descriptor_t task;\n\t\t/* end of the kernel processed data */\n\t\tNDR_record_t NDR;\n\t\texception_type_t exception;\n\t\tmach_msg_type_number_t codeCnt;\n\t\tint64_t code[2];\n\t} __Request__mach_exception_raise_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\tNDR_record_t NDR;\n\t\texception_type_t exception;\n\t\tmach_msg_type_number_t codeCnt;\n\t\tint64_t code[2];\n\t\tint flavor;\n\t\tmach_msg_type_number_t old_stateCnt;\n\t\tnatural_t old_state[614];\n\t} __Request__mach_exception_raise_state_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\t/* start of the kernel processed data */\n\t\tmach_msg_body_t msgh_body;\n\t\tmach_msg_port_descriptor_t thread;\n\t\tmach_msg_port_descriptor_t task;\n\t\t/* end of the kernel processed data */\n\t\tNDR_record_t NDR;\n\t\texception_type_t exception;\n\t\tmach_msg_type_number_t codeCnt;\n\t\tint64_t code[2];\n\t\tint flavor;\n\t\tmach_msg_type_number_t old_stateCnt;\n\t\tnatural_t old_state[614];\n\t} __Request__mach_exception_raise_state_identity_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n#endif /* !__Request__mach_exc_subsystem__defined */\n\n/* union of all requests */\n\n#ifndef __RequestUnion__mach_exc_subsystem__defined\n#define __RequestUnion__mach_exc_subsystem__defined\nunion __RequestUnion__mach_exc_subsystem {\n\t__Request__mach_exception_raise_t Request_mach_exception_raise;\n\t__Request__mach_exception_raise_state_t Request_mach_exception_raise_state;\n\t__Request__mach_exception_raise_state_identity_t Request_mach_exception_raise_state_identity;\n};\n#endif /* !__RequestUnion__mach_exc_subsystem__defined */\n/* typedefs for all replies */\n\n#ifndef __Reply__mach_exc_subsystem__defined\n#define __Reply__mach_exc_subsystem__defined\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\tNDR_record_t NDR;\n\t\tkern_return_t RetCode;\n\t} __Reply__mach_exception_raise_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\tNDR_record_t NDR;\n\t\tkern_return_t RetCode;\n\t\tint flavor;\n\t\tmach_msg_type_number_t new_stateCnt;\n\t\tnatural_t new_state[614];\n\t} __Reply__mach_exception_raise_state_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\tNDR_record_t NDR;\n\t\tkern_return_t RetCode;\n\t\tint flavor;\n\t\tmach_msg_type_number_t new_stateCnt;\n\t\tnatural_t new_state[614];\n\t} __Reply__mach_exception_raise_state_identity_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n#endif /* !__Reply__mach_exc_subsystem__defined */\n\n/* union of all replies */\n\n#ifndef __ReplyUnion__mach_exc_subsystem__defined\n#define __ReplyUnion__mach_exc_subsystem__defined\nunion __ReplyUnion__mach_exc_subsystem {\n\t__Reply__mach_exception_raise_t Reply_mach_exception_raise;\n\t__Reply__mach_exception_raise_state_t Reply_mach_exception_raise_state;\n\t__Reply__mach_exception_raise_state_identity_t Reply_mach_exception_raise_state_identity;\n};\n#endif /* !__RequestUnion__mach_exc_subsystem__defined */\n\n#ifndef subsystem_to_name_map_mach_exc\n#define subsystem_to_name_map_mach_exc \\\n    { \"mach_exception_raise\", 2405 },\\\n    { \"mach_exception_raise_state\", 2406 },\\\n    { \"mach_exception_raise_state_identity\", 2407 }\n#endif\n\n#ifdef __AfterMigUserHeader\n__AfterMigUserHeader\n#endif /* __AfterMigUserHeader */\n\n#endif\t /* _mach_exc_user_ */\n"
  },
  {
    "path": "src/macos/mach_excServer.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * this code is generated automatically by mig\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n/*\n * IDENTIFICATION:\n * stub generated Mon Nov  7 09:48:39 2022\n * with a MiG generated by bootstrap_cmds-117\n * OPTIONS: \n */\n\n/* Module mach_exc */\n\n#define\t__MIG_check__Request__mach_exc_subsystem__ 1\n#include <string.h>\n#include <mach/ndr.h>\n#include <mach/boolean.h>\n#include <mach/kern_return.h>\n#include <mach/notify.h>\n#include <mach/mach_types.h>\n#include <mach/message.h>\n#include <mach/mig_errors.h>\n#include <mach/port.h>\n#include \"injector_internal.h\"\n/* BEGIN VOUCHER CODE */\n\n#ifndef KERNEL\n#if defined(__has_include)\n#if __has_include(<mach/mig_voucher_support.h>)\n#ifndef USING_VOUCHERS\n#define USING_VOUCHERS\n#endif\n#ifndef __VOUCHER_FORWARD_TYPE_DECLS__\n#define __VOUCHER_FORWARD_TYPE_DECLS__\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\textern boolean_t voucher_mach_msg_set(mach_msg_header_t *msg) __attribute__((weak_import));\n#ifdef __cplusplus\n}\n#endif\n#endif // __VOUCHER_FORWARD_TYPE_DECLS__\n#endif // __has_include(<mach/mach_voucher_types.h>)\n#endif // __has_include\n#endif // !KERNEL\n\t\n/* END VOUCHER CODE */\n\n\t\n/* BEGIN MIG_STRNCPY_ZEROFILL CODE */\n\n#if defined(__has_include)\n#if __has_include(<mach/mig_strncpy_zerofill_support.h>)\n#ifndef USING_MIG_STRNCPY_ZEROFILL\n#define USING_MIG_STRNCPY_ZEROFILL\n#endif\n#ifndef __MIG_STRNCPY_ZEROFILL_FORWARD_TYPE_DECLS__\n#define __MIG_STRNCPY_ZEROFILL_FORWARD_TYPE_DECLS__\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\textern int mig_strncpy_zerofill(char *dest, const char *src, int len) __attribute__((weak_import));\n#ifdef __cplusplus\n}\n#endif\n#endif /* __MIG_STRNCPY_ZEROFILL_FORWARD_TYPE_DECLS__ */\n#endif /* __has_include(<mach/mig_strncpy_zerofill_support.h>) */\n#endif /* __has_include */\n\t\n/* END MIG_STRNCPY_ZEROFILL CODE */\n\n\n#include <mach/std_types.h>\n#include <mach/mig.h>\n#include <mach/mig.h>\n#include <mach/mach_types.h>\n\n#ifndef\tmig_internal\n#define\tmig_internal\tstatic __inline__\n#endif\t/* mig_internal */\n\n#ifndef\tmig_external\n#define mig_external\n#endif\t/* mig_external */\n\n#if\t!defined(__MigTypeCheck) && defined(TypeCheck)\n#define\t__MigTypeCheck\t\tTypeCheck\t/* Legacy setting */\n#endif\t/* !defined(__MigTypeCheck) */\n\n#if\t!defined(__MigKernelSpecificCode) && defined(_MIG_KERNEL_SPECIFIC_CODE_)\n#define\t__MigKernelSpecificCode\t_MIG_KERNEL_SPECIFIC_CODE_\t/* Legacy setting */\n#endif\t/* !defined(__MigKernelSpecificCode) */\n\n#ifndef\tLimitCheck\n#define\tLimitCheck 0\n#endif\t/* LimitCheck */\n\n#ifndef\tmin\n#define\tmin(a,b)  ( ((a) < (b))? (a): (b) )\n#endif\t/* min */\n\n#if !defined(_WALIGN_)\n#define _WALIGN_(x) (((x) + 3) & ~3)\n#endif /* !defined(_WALIGN_) */\n\n#if !defined(_WALIGNSZ_)\n#define _WALIGNSZ_(x) _WALIGN_(sizeof(x))\n#endif /* !defined(_WALIGNSZ_) */\n\n#ifndef\tUseStaticTemplates\n#define\tUseStaticTemplates\t0\n#endif\t/* UseStaticTemplates */\n\n#ifndef MIG_SERVER_ROUTINE\n#define MIG_SERVER_ROUTINE\n#endif\n\n#ifndef\t__DeclareRcvRpc\n#define\t__DeclareRcvRpc(_NUM_, _NAME_)\n#endif\t/* __DeclareRcvRpc */\n\n#ifndef\t__BeforeRcvRpc\n#define\t__BeforeRcvRpc(_NUM_, _NAME_)\n#endif\t/* __BeforeRcvRpc */\n\n#ifndef\t__AfterRcvRpc\n#define\t__AfterRcvRpc(_NUM_, _NAME_)\n#endif\t/* __AfterRcvRpc */\n\n#ifndef\t__DeclareRcvSimple\n#define\t__DeclareRcvSimple(_NUM_, _NAME_)\n#endif\t/* __DeclareRcvSimple */\n\n#ifndef\t__BeforeRcvSimple\n#define\t__BeforeRcvSimple(_NUM_, _NAME_)\n#endif\t/* __BeforeRcvSimple */\n\n#ifndef\t__AfterRcvSimple\n#define\t__AfterRcvSimple(_NUM_, _NAME_)\n#endif\t/* __AfterRcvSimple */\n\n#define novalue void\n\n#define msgh_request_port\tmsgh_local_port\n#define MACH_MSGH_BITS_REQUEST(bits)\tMACH_MSGH_BITS_LOCAL(bits)\n#define msgh_reply_port\t\tmsgh_remote_port\n#define MACH_MSGH_BITS_REPLY(bits)\tMACH_MSGH_BITS_REMOTE(bits)\n\n#define MIG_RETURN_ERROR(X, code)\t{\\\n\t\t\t\t((mig_reply_error_t *)X)->RetCode = code;\\\n\t\t\t\t((mig_reply_error_t *)X)->NDR = NDR_record;\\\n\t\t\t\treturn;\\\n\t\t\t\t}\n\n/* typedefs for all requests */\n\n#ifndef __Request__mach_exc_subsystem__defined\n#define __Request__mach_exc_subsystem__defined\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\t/* start of the kernel processed data */\n\t\tmach_msg_body_t msgh_body;\n\t\tmach_msg_port_descriptor_t thread;\n\t\tmach_msg_port_descriptor_t task;\n\t\t/* end of the kernel processed data */\n\t\tNDR_record_t NDR;\n\t\texception_type_t exception;\n\t\tmach_msg_type_number_t codeCnt;\n\t\tint64_t code[2];\n\t} __Request__mach_exception_raise_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\tNDR_record_t NDR;\n\t\texception_type_t exception;\n\t\tmach_msg_type_number_t codeCnt;\n\t\tint64_t code[2];\n\t\tint flavor;\n\t\tmach_msg_type_number_t old_stateCnt;\n\t\tnatural_t old_state[614];\n\t} __Request__mach_exception_raise_state_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\t/* start of the kernel processed data */\n\t\tmach_msg_body_t msgh_body;\n\t\tmach_msg_port_descriptor_t thread;\n\t\tmach_msg_port_descriptor_t task;\n\t\t/* end of the kernel processed data */\n\t\tNDR_record_t NDR;\n\t\texception_type_t exception;\n\t\tmach_msg_type_number_t codeCnt;\n\t\tint64_t code[2];\n\t\tint flavor;\n\t\tmach_msg_type_number_t old_stateCnt;\n\t\tnatural_t old_state[614];\n\t} __Request__mach_exception_raise_state_identity_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n#endif /* !__Request__mach_exc_subsystem__defined */\n\n/* typedefs for all replies */\n\n#ifndef __Reply__mach_exc_subsystem__defined\n#define __Reply__mach_exc_subsystem__defined\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\tNDR_record_t NDR;\n\t\tkern_return_t RetCode;\n\t} __Reply__mach_exception_raise_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\tNDR_record_t NDR;\n\t\tkern_return_t RetCode;\n\t\tint flavor;\n\t\tmach_msg_type_number_t new_stateCnt;\n\t\tnatural_t new_state[614];\n\t} __Reply__mach_exception_raise_state_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\tNDR_record_t NDR;\n\t\tkern_return_t RetCode;\n\t\tint flavor;\n\t\tmach_msg_type_number_t new_stateCnt;\n\t\tnatural_t new_state[614];\n\t} __Reply__mach_exception_raise_state_identity_t __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n#endif /* !__Reply__mach_exc_subsystem__defined */\n\n\n/* union of all replies */\n\n#ifndef __ReplyUnion__catch_mach_exc_subsystem__defined\n#define __ReplyUnion__catch_mach_exc_subsystem__defined\nunion __ReplyUnion__catch_mach_exc_subsystem {\n\t__Reply__mach_exception_raise_t Reply_mach_exception_raise;\n\t__Reply__mach_exception_raise_state_t Reply_mach_exception_raise_state;\n\t__Reply__mach_exception_raise_state_identity_t Reply_mach_exception_raise_state_identity;\n};\n#endif /* __ReplyUnion__catch_mach_exc_subsystem__defined */\n/* Forward Declarations */\n\n\nmig_internal novalue _Xmach_exception_raise\n\t(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);\n\nmig_internal novalue _Xmach_exception_raise_state\n\t(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);\n\nmig_internal novalue _Xmach_exception_raise_state_identity\n\t(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);\n\n\n#if ( __MigTypeCheck )\n#if __MIG_check__Request__mach_exc_subsystem__\n#if !defined(__MIG_check__Request__mach_exception_raise_t__defined)\n#define __MIG_check__Request__mach_exception_raise_t__defined\n\nmig_internal kern_return_t __MIG_check__Request__mach_exception_raise_t(__attribute__((__unused__)) __Request__mach_exception_raise_t *In0P)\n{\n\n\ttypedef __Request__mach_exception_raise_t __Request;\n#if\t__MigTypeCheck\n\tunsigned int msgh_size;\n#endif\t/* __MigTypeCheck */\n\n#if\t__MigTypeCheck\n\tmsgh_size = In0P->Head.msgh_size;\n\tif (!(In0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||\n\t    (In0P->msgh_body.msgh_descriptor_count != 2) ||\n\t    (msgh_size < (mach_msg_size_t)(sizeof(__Request) - 16)) ||  (msgh_size > (mach_msg_size_t)sizeof(__Request)))\n\t\treturn MIG_BAD_ARGUMENTS;\n#endif\t/* __MigTypeCheck */\n\n#if\t__MigTypeCheck\n\tif (In0P->thread.type != MACH_MSG_PORT_DESCRIPTOR ||\n\t    In0P->thread.disposition != 17)\n\t\treturn MIG_TYPE_ERROR;\n#endif\t/* __MigTypeCheck */\n\n#if\t__MigTypeCheck\n\tif (In0P->task.type != MACH_MSG_PORT_DESCRIPTOR ||\n\t    In0P->task.disposition != 17)\n\t\treturn MIG_TYPE_ERROR;\n#endif\t/* __MigTypeCheck */\n\n#if defined(__NDR_convert__int_rep__Request__mach_exception_raise_t__codeCnt__defined)\n\tif (In0P->NDR.int_rep != NDR_record.int_rep)\n\t\t__NDR_convert__int_rep__Request__mach_exception_raise_t__codeCnt(&In0P->codeCnt, In0P->NDR.int_rep);\n#endif\t/* __NDR_convert__int_rep__Request__mach_exception_raise_t__codeCnt__defined */\n#if\t__MigTypeCheck\n\tif ( In0P->codeCnt > 2 )\n\t\treturn MIG_BAD_ARGUMENTS;\n\tif (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 16)) / 8 < In0P->codeCnt) ||\n\t    (msgh_size != (mach_msg_size_t)(sizeof(__Request) - 16) + (8 * In0P->codeCnt)))\n\t\treturn MIG_BAD_ARGUMENTS;\n#endif\t/* __MigTypeCheck */\n\n\treturn MACH_MSG_SUCCESS;\n}\n#endif /* !defined(__MIG_check__Request__mach_exception_raise_t__defined) */\n#endif /* __MIG_check__Request__mach_exc_subsystem__ */\n#endif /* ( __MigTypeCheck ) */\n\n\n/* Routine mach_exception_raise */\n#ifdef\tmig_external\nmig_external\n#else\nextern\n#endif\t/* mig_external */\nMIG_SERVER_ROUTINE\nkern_return_t catch_mach_exception_raise\n(\n\tmach_port_t exception_port,\n\tmach_port_t thread,\n\tmach_port_t task,\n\texception_type_t exception,\n\tmach_exception_data_t code,\n\tmach_msg_type_number_t codeCnt,\n\tinjector_t *injector\n);\n\n/* Routine mach_exception_raise */\nmig_internal novalue _Xmach_exception_raise\n\t(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)\n{\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\t/* start of the kernel processed data */\n\t\tmach_msg_body_t msgh_body;\n\t\tmach_msg_port_descriptor_t thread;\n\t\tmach_msg_port_descriptor_t task;\n\t\t/* end of the kernel processed data */\n\t\tNDR_record_t NDR;\n\t\texception_type_t exception;\n\t\tmach_msg_type_number_t codeCnt;\n\t\tint64_t code[2];\n\t\tmach_msg_trailer_t trailer;\n\t} Request __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\ttypedef __Request__mach_exception_raise_t __Request;\n\ttypedef __Reply__mach_exception_raise_t Reply __attribute__((unused));\n\n\t/*\n\t * typedef struct {\n\t * \tmach_msg_header_t Head;\n\t * \tNDR_record_t NDR;\n\t * \tkern_return_t RetCode;\n\t * } mig_reply_error_t;\n\t */\n\tRequest *In0P = (Request *) InHeadP;\n\tReply *OutP = (Reply *) OutHeadP;\n#ifdef\t__MIG_check__Request__mach_exception_raise_t__defined\n\tkern_return_t check_result;\n#endif\t/* __MIG_check__Request__mach_exception_raise_t__defined */\n\n\t__DeclareRcvRpc(2405, \"mach_exception_raise\")\n\t__BeforeRcvRpc(2405, \"mach_exception_raise\")\n\n#if\tdefined(__MIG_check__Request__mach_exception_raise_t__defined)\n\tcheck_result = __MIG_check__Request__mach_exception_raise_t((__Request *)In0P);\n\tif (check_result != MACH_MSG_SUCCESS)\n\t\t{ MIG_RETURN_ERROR(OutP, check_result); }\n#endif\t/* defined(__MIG_check__Request__mach_exception_raise_t__defined) */\n\tmach_msg_header_with_injector *mmhwi = (mach_msg_header_with_injector*)In0P;\n\tOutP->RetCode = catch_mach_exception_raise(In0P->Head.msgh_request_port, In0P->thread.name, In0P->task.name, In0P->exception, In0P->code, In0P->codeCnt, mmhwi->injector);\n\n\tOutP->NDR = NDR_record;\n\n\n\t__AfterRcvRpc(2405, \"mach_exception_raise\")\n}\n\n#if ( __MigTypeCheck )\n#if __MIG_check__Request__mach_exc_subsystem__\n#if !defined(__MIG_check__Request__mach_exception_raise_state_t__defined)\n#define __MIG_check__Request__mach_exception_raise_state_t__defined\n\nmig_internal kern_return_t __MIG_check__Request__mach_exception_raise_state_t(__attribute__((__unused__)) __Request__mach_exception_raise_state_t *In0P, __attribute__((__unused__)) __Request__mach_exception_raise_state_t **In1PP)\n{\n\n\ttypedef __Request__mach_exception_raise_state_t __Request;\n\t__Request *In1P;\n#if\t__MigTypeCheck\n\tunsigned int msgh_size;\n#endif\t/* __MigTypeCheck */\n\tunsigned int msgh_size_delta;\n\n#if\t__MigTypeCheck\n\tmsgh_size = In0P->Head.msgh_size;\n\tif ((In0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||\n\t    (msgh_size < (mach_msg_size_t)(sizeof(__Request) - 2472)) ||  (msgh_size > (mach_msg_size_t)sizeof(__Request)))\n\t\treturn MIG_BAD_ARGUMENTS;\n#endif\t/* __MigTypeCheck */\n\n#if defined(__NDR_convert__int_rep__Request__mach_exception_raise_state_t__codeCnt__defined)\n\tif (In0P->NDR.int_rep != NDR_record.int_rep)\n\t\t__NDR_convert__int_rep__Request__mach_exception_raise_state_t__codeCnt(&In0P->codeCnt, In0P->NDR.int_rep);\n#endif\t/* __NDR_convert__int_rep__Request__mach_exception_raise_state_t__codeCnt__defined */\n\tmsgh_size_delta = (8 * In0P->codeCnt);\n#if\t__MigTypeCheck\n\tif ( In0P->codeCnt > 2 )\n\t\treturn MIG_BAD_ARGUMENTS;\n\tif (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 2472)) / 8 < In0P->codeCnt) ||\n\t    (msgh_size < (mach_msg_size_t)(sizeof(__Request) - 2472) + (8 * In0P->codeCnt)))\n\t\treturn MIG_BAD_ARGUMENTS;\n\tmsgh_size -= msgh_size_delta;\n#endif\t/* __MigTypeCheck */\n\n\t*In1PP = In1P = (__Request *) ((pointer_t) In0P + msgh_size_delta - 16);\n\n#if defined(__NDR_convert__int_rep__Request__mach_exception_raise_state_t__old_stateCnt__defined)\n\tif (In0P->NDR.int_rep != NDR_record.int_rep)\n\t\t__NDR_convert__int_rep__Request__mach_exception_raise_state_t__old_stateCnt(&In1P->old_stateCnt, In1P->NDR.int_rep);\n#endif\t/* __NDR_convert__int_rep__Request__mach_exception_raise_state_t__old_stateCnt__defined */\n#if\t__MigTypeCheck\n\tif ( In1P->old_stateCnt > 614 )\n\t\treturn MIG_BAD_ARGUMENTS;\n\tif (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 2472)) / 4 < In1P->old_stateCnt) ||\n\t    (msgh_size != (mach_msg_size_t)(sizeof(__Request) - 2472) + (4 * In1P->old_stateCnt)))\n\t\treturn MIG_BAD_ARGUMENTS;\n#endif\t/* __MigTypeCheck */\n\n\treturn MACH_MSG_SUCCESS;\n}\n#endif /* !defined(__MIG_check__Request__mach_exception_raise_state_t__defined) */\n#endif /* __MIG_check__Request__mach_exc_subsystem__ */\n#endif /* ( __MigTypeCheck ) */\n\n\n/* Routine mach_exception_raise_state */\n#ifdef\tmig_external\nmig_external\n#else\nextern\n#endif\t/* mig_external */\nMIG_SERVER_ROUTINE\nkern_return_t catch_mach_exception_raise_state\n(\n\tmach_port_t exception_port,\n\texception_type_t exception,\n\tconst mach_exception_data_t code,\n\tmach_msg_type_number_t codeCnt,\n\tint *flavor,\n\tconst thread_state_t old_state,\n\tmach_msg_type_number_t old_stateCnt,\n\tthread_state_t new_state,\n\tmach_msg_type_number_t *new_stateCnt\n);\n\n/* Routine mach_exception_raise_state */\nmig_internal novalue _Xmach_exception_raise_state\n\t(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)\n{\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\tNDR_record_t NDR;\n\t\texception_type_t exception;\n\t\tmach_msg_type_number_t codeCnt;\n\t\tint64_t code[2];\n\t\tint flavor;\n\t\tmach_msg_type_number_t old_stateCnt;\n\t\tnatural_t old_state[614];\n\t\tmach_msg_trailer_t trailer;\n\t} Request __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\ttypedef __Request__mach_exception_raise_state_t __Request;\n\ttypedef __Reply__mach_exception_raise_state_t Reply __attribute__((unused));\n\n\t/*\n\t * typedef struct {\n\t * \tmach_msg_header_t Head;\n\t * \tNDR_record_t NDR;\n\t * \tkern_return_t RetCode;\n\t * } mig_reply_error_t;\n\t */\n\n\tRequest *In0P = (Request *) InHeadP;\n\tRequest *In1P;\n\tReply *OutP = (Reply *) OutHeadP;\n#ifdef\t__MIG_check__Request__mach_exception_raise_state_t__defined\n\tkern_return_t check_result;\n#endif\t/* __MIG_check__Request__mach_exception_raise_state_t__defined */\n\n\t__DeclareRcvRpc(2406, \"mach_exception_raise_state\")\n\t__BeforeRcvRpc(2406, \"mach_exception_raise_state\")\n\n#if\tdefined(__MIG_check__Request__mach_exception_raise_state_t__defined)\n\tcheck_result = __MIG_check__Request__mach_exception_raise_state_t((__Request *)In0P, (__Request **)&In1P);\n\tif (check_result != MACH_MSG_SUCCESS)\n\t\t{ MIG_RETURN_ERROR(OutP, check_result); }\n#endif\t/* defined(__MIG_check__Request__mach_exception_raise_state_t__defined) */\n\n\tOutP->new_stateCnt = 614;\n\n\tOutP->RetCode = catch_mach_exception_raise_state(In0P->Head.msgh_request_port, In0P->exception, In0P->code, In0P->codeCnt, &In1P->flavor, In1P->old_state, In1P->old_stateCnt, OutP->new_state, &OutP->new_stateCnt);\n\tif (OutP->RetCode != KERN_SUCCESS) {\n\t\tMIG_RETURN_ERROR(OutP, OutP->RetCode);\n\t}\n\n\tOutP->NDR = NDR_record;\n\n\n\tOutP->flavor = In1P->flavor;\n\tOutP->Head.msgh_size = (mach_msg_size_t)(sizeof(Reply) - 2456) + (((4 * OutP->new_stateCnt)));\n\n\t__AfterRcvRpc(2406, \"mach_exception_raise_state\")\n}\n\n#if ( __MigTypeCheck )\n#if __MIG_check__Request__mach_exc_subsystem__\n#if !defined(__MIG_check__Request__mach_exception_raise_state_identity_t__defined)\n#define __MIG_check__Request__mach_exception_raise_state_identity_t__defined\n\nmig_internal kern_return_t __MIG_check__Request__mach_exception_raise_state_identity_t(__attribute__((__unused__)) __Request__mach_exception_raise_state_identity_t *In0P, __attribute__((__unused__)) __Request__mach_exception_raise_state_identity_t **In1PP)\n{\n\n\ttypedef __Request__mach_exception_raise_state_identity_t __Request;\n\t__Request *In1P;\n#if\t__MigTypeCheck\n\tunsigned int msgh_size;\n#endif\t/* __MigTypeCheck */\n\tunsigned int msgh_size_delta;\n\n#if\t__MigTypeCheck\n\tmsgh_size = In0P->Head.msgh_size;\n\tif (!(In0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||\n\t    (In0P->msgh_body.msgh_descriptor_count != 2) ||\n\t    (msgh_size < (mach_msg_size_t)(sizeof(__Request) - 2472)) ||  (msgh_size > (mach_msg_size_t)sizeof(__Request)))\n\t\treturn MIG_BAD_ARGUMENTS;\n#endif\t/* __MigTypeCheck */\n\n#if\t__MigTypeCheck\n\tif (In0P->thread.type != MACH_MSG_PORT_DESCRIPTOR ||\n\t    In0P->thread.disposition != 17)\n\t\treturn MIG_TYPE_ERROR;\n#endif\t/* __MigTypeCheck */\n\n#if\t__MigTypeCheck\n\tif (In0P->task.type != MACH_MSG_PORT_DESCRIPTOR ||\n\t    In0P->task.disposition != 17)\n\t\treturn MIG_TYPE_ERROR;\n#endif\t/* __MigTypeCheck */\n\n#if defined(__NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__codeCnt__defined)\n\tif (In0P->NDR.int_rep != NDR_record.int_rep)\n\t\t__NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__codeCnt(&In0P->codeCnt, In0P->NDR.int_rep);\n#endif\t/* __NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__codeCnt__defined */\n\tmsgh_size_delta = (8 * In0P->codeCnt);\n#if\t__MigTypeCheck\n\tif ( In0P->codeCnt > 2 )\n\t\treturn MIG_BAD_ARGUMENTS;\n\tif (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 2472)) / 8 < In0P->codeCnt) ||\n\t    (msgh_size < (mach_msg_size_t)(sizeof(__Request) - 2472) + (8 * In0P->codeCnt)))\n\t\treturn MIG_BAD_ARGUMENTS;\n\tmsgh_size -= msgh_size_delta;\n#endif\t/* __MigTypeCheck */\n\n\t*In1PP = In1P = (__Request *) ((pointer_t) In0P + msgh_size_delta - 16);\n\n#if defined(__NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__old_stateCnt__defined)\n\tif (In0P->NDR.int_rep != NDR_record.int_rep)\n\t\t__NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__old_stateCnt(&In1P->old_stateCnt, In1P->NDR.int_rep);\n#endif\t/* __NDR_convert__int_rep__Request__mach_exception_raise_state_identity_t__old_stateCnt__defined */\n#if\t__MigTypeCheck\n\tif ( In1P->old_stateCnt > 614 )\n\t\treturn MIG_BAD_ARGUMENTS;\n\tif (((msgh_size - (mach_msg_size_t)(sizeof(__Request) - 2472)) / 4 < In1P->old_stateCnt) ||\n\t    (msgh_size != (mach_msg_size_t)(sizeof(__Request) - 2472) + (4 * In1P->old_stateCnt)))\n\t\treturn MIG_BAD_ARGUMENTS;\n#endif\t/* __MigTypeCheck */\n\n\treturn MACH_MSG_SUCCESS;\n}\n#endif /* !defined(__MIG_check__Request__mach_exception_raise_state_identity_t__defined) */\n#endif /* __MIG_check__Request__mach_exc_subsystem__ */\n#endif /* ( __MigTypeCheck ) */\n\n\n/* Routine mach_exception_raise_state_identity */\n#ifdef\tmig_external\nmig_external\n#else\nextern\n#endif\t/* mig_external */\nMIG_SERVER_ROUTINE\nkern_return_t catch_mach_exception_raise_state_identity\n(\n\tmach_port_t exception_port,\n\tmach_port_t thread,\n\tmach_port_t task,\n\texception_type_t exception,\n\tmach_exception_data_t code,\n\tmach_msg_type_number_t codeCnt,\n\tint *flavor,\n\tthread_state_t old_state,\n\tmach_msg_type_number_t old_stateCnt,\n\tthread_state_t new_state,\n\tmach_msg_type_number_t *new_stateCnt\n);\n\n/* Routine mach_exception_raise_state_identity */\nmig_internal novalue _Xmach_exception_raise_state_identity\n\t(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)\n{\n\n#ifdef  __MigPackStructs\n#pragma pack(push, 4)\n#endif\n\ttypedef struct {\n\t\tmach_msg_header_t Head;\n\t\t/* start of the kernel processed data */\n\t\tmach_msg_body_t msgh_body;\n\t\tmach_msg_port_descriptor_t thread;\n\t\tmach_msg_port_descriptor_t task;\n\t\t/* end of the kernel processed data */\n\t\tNDR_record_t NDR;\n\t\texception_type_t exception;\n\t\tmach_msg_type_number_t codeCnt;\n\t\tint64_t code[2];\n\t\tint flavor;\n\t\tmach_msg_type_number_t old_stateCnt;\n\t\tnatural_t old_state[614];\n\t\tmach_msg_trailer_t trailer;\n\t} Request __attribute__((unused));\n#ifdef  __MigPackStructs\n#pragma pack(pop)\n#endif\n\ttypedef __Request__mach_exception_raise_state_identity_t __Request;\n\ttypedef __Reply__mach_exception_raise_state_identity_t Reply __attribute__((unused));\n\n\t/*\n\t * typedef struct {\n\t * \tmach_msg_header_t Head;\n\t * \tNDR_record_t NDR;\n\t * \tkern_return_t RetCode;\n\t * } mig_reply_error_t;\n\t */\n\n\tRequest *In0P = (Request *) InHeadP;\n\tRequest *In1P;\n\tReply *OutP = (Reply *) OutHeadP;\n#ifdef\t__MIG_check__Request__mach_exception_raise_state_identity_t__defined\n\tkern_return_t check_result;\n#endif\t/* __MIG_check__Request__mach_exception_raise_state_identity_t__defined */\n\n\t__DeclareRcvRpc(2407, \"mach_exception_raise_state_identity\")\n\t__BeforeRcvRpc(2407, \"mach_exception_raise_state_identity\")\n\n#if\tdefined(__MIG_check__Request__mach_exception_raise_state_identity_t__defined)\n\tcheck_result = __MIG_check__Request__mach_exception_raise_state_identity_t((__Request *)In0P, (__Request **)&In1P);\n\tif (check_result != MACH_MSG_SUCCESS)\n\t\t{ MIG_RETURN_ERROR(OutP, check_result); }\n#endif\t/* defined(__MIG_check__Request__mach_exception_raise_state_identity_t__defined) */\n\n\tOutP->new_stateCnt = 614;\n\n\tOutP->RetCode = catch_mach_exception_raise_state_identity(In0P->Head.msgh_request_port, In0P->thread.name, In0P->task.name, In0P->exception, In0P->code, In0P->codeCnt, &In1P->flavor, In1P->old_state, In1P->old_stateCnt, OutP->new_state, &OutP->new_stateCnt);\n\tif (OutP->RetCode != KERN_SUCCESS) {\n\t\tMIG_RETURN_ERROR(OutP, OutP->RetCode);\n\t}\n\n\tOutP->NDR = NDR_record;\n\n\n\tOutP->flavor = In1P->flavor;\n\tOutP->Head.msgh_size = (mach_msg_size_t)(sizeof(Reply) - 2456) + (((4 * OutP->new_stateCnt)));\n\n\t__AfterRcvRpc(2407, \"mach_exception_raise_state_identity\")\n}\n\n\n#ifdef\tmig_external\nmig_external\n#else\nextern\n#endif\t/* mig_external */\nboolean_t mach_exc_server(\n\t\tmach_msg_header_t *InHeadP,\n\t\tmach_msg_header_t *OutHeadP);\n\n#ifdef\tmig_external\nmig_external\n#else\nextern\n#endif\t/* mig_external */\nmig_routine_t mach_exc_server_routine(\n\t\tmach_msg_header_t *InHeadP);\n\n\n/* Description of this subsystem, for use in direct RPC */\nconst struct catch_mach_exc_subsystem {\n\tmig_server_routine_t \tserver;\t/* Server routine */\n\tmach_msg_id_t\tstart;\t/* Min routine number */\n\tmach_msg_id_t\tend;\t/* Max routine number + 1 */\n\tunsigned int\tmaxsize;\t/* Max msg size */\n\tvm_address_t\treserved;\t/* Reserved */\n\tstruct routine_descriptor\t/*Array of routine descriptors */\n\t\troutine[3];\n} catch_mach_exc_subsystem = {\n\tmach_exc_server_routine,\n\t2405,\n\t2408,\n\t(mach_msg_size_t)sizeof(union __ReplyUnion__catch_mach_exc_subsystem),\n\t(vm_address_t)0,\n\t{\n          { (mig_impl_routine_t) 0,\n          (mig_stub_routine_t) _Xmach_exception_raise, 6, 0, (routine_arg_descriptor_t)0, (mach_msg_size_t)sizeof(__Reply__mach_exception_raise_t)},\n          { (mig_impl_routine_t) 0,\n          (mig_stub_routine_t) _Xmach_exception_raise_state, 9, 0, (routine_arg_descriptor_t)0, (mach_msg_size_t)sizeof(__Reply__mach_exception_raise_state_t)},\n          { (mig_impl_routine_t) 0,\n          (mig_stub_routine_t) _Xmach_exception_raise_state_identity, 11, 0, (routine_arg_descriptor_t)0, (mach_msg_size_t)sizeof(__Reply__mach_exception_raise_state_identity_t)},\n\t}\n};\n\nmig_external boolean_t mach_exc_server\n\t(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)\n{\n\t/*\n\t * typedef struct {\n\t * \tmach_msg_header_t Head;\n\t * \tNDR_record_t NDR;\n\t * \tkern_return_t RetCode;\n\t * } mig_reply_error_t;\n\t */\n\n\tmig_routine_t routine;\n\n\tOutHeadP->msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REPLY(InHeadP->msgh_bits), 0);\n\tOutHeadP->msgh_remote_port = InHeadP->msgh_reply_port;\n\t/* Minimal size: routine() will update it if different */\n\tOutHeadP->msgh_size = (mach_msg_size_t)sizeof(mig_reply_error_t);\n\tOutHeadP->msgh_local_port = MACH_PORT_NULL;\n\tOutHeadP->msgh_id = InHeadP->msgh_id + 100;\n\tOutHeadP->msgh_reserved = 0;\n\n\tif ((InHeadP->msgh_id > 2407) || (InHeadP->msgh_id < 2405) ||\n\t    ((routine = catch_mach_exc_subsystem.routine[InHeadP->msgh_id - 2405].stub_routine) == 0)) {\n\t\t((mig_reply_error_t *)OutHeadP)->NDR = NDR_record;\n\t\t((mig_reply_error_t *)OutHeadP)->RetCode = MIG_BAD_ID;\n\t\treturn FALSE;\n\t}\n\t(*routine) (InHeadP, OutHeadP);\n\treturn TRUE;\n}\n\nmig_external mig_routine_t mach_exc_server_routine\n\t(mach_msg_header_t *InHeadP)\n{\n\tint msgh_id;\n\n\tmsgh_id = InHeadP->msgh_id - 2405;\n\n\tif ((msgh_id > 2) || (msgh_id < 0))\n\t\treturn 0;\n\n\treturn catch_mach_exc_subsystem.routine[msgh_id].stub_routine;\n}\n"
  },
  {
    "path": "src/macos/ptrace.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2022 TheOiseth\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include \"injector_internal.h\"\n#include <libproc.h>\n#include <signal.h>\n#include <sys/types.h>\n#include <sys/ptrace.h>\n#define PTRACE_OR_RETURN(request, injector, addr, data) do { \\\n    int rv = injector__ptrace(request, injector->pid, addr, data, #request); \\\n    if (rv != 0) { \\\n        return rv; \\\n    } \\\n} while (0)\nstatic int set_ptrace_error(const char *request_name)\n{\n    int err = errno;\n    injector__set_errmsg(\"%s error : %s\", request_name, strerror(errno));\n    switch (err) {\n    case EFAULT:\n        return INJERR_INVALID_MEMORY_AREA;\n    case EPERM:\n        return INJERR_PERMISSION;\n    case ESRCH:\n        return INJERR_NO_PROCESS;\n    }\n    return INJERR_OTHER;\n}\n\nint injector__ptrace(int request, pid_t pid, long addr, long data, const char *request_name)\n{\n    if (ptrace(request, pid, (caddr_t)addr, data) != 0) {\n        return set_ptrace_error(request_name);\n    }\n    return 0;\n}\n\nint injector__ptrace_attach(const injector_t *injector)\n{\n    PTRACE_OR_RETURN(PT_ATTACHEXC, injector, 0, 0);\n    return 0;\n}\n\nint injector__ptrace_detach(const injector_t *injector)\n{\n    PTRACE_OR_RETURN(PT_DETACH, injector, 0, 0);\n    return 0;\n}\n\nint injector__ptrace_continue(const injector_t *injector)\n{\n    PTRACE_OR_RETURN(PT_CONTINUE, injector, 1, 0);\n    return 0;\n}\n\nint injector__ptrace_update(const injector_t *injector, long thread_port)\n{\n    PTRACE_OR_RETURN(PT_THUPDATE, injector, thread_port, 0);\n    return 0;\n}"
  },
  {
    "path": "src/macos/remote_call.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2022 TheOiseth\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include \"injector_internal.h\"\n#include \"mach_exc.h\"\n#include <stdlib.h>\n#include <dlfcn.h>\n#include <stdio.h>\n#include <sys/types.h>\n#include <sys/ptrace.h>\n#include <signal.h>\n\n//Before change shellcode, see:\n//injector.c -> injector_detach\n//exc_handler.c -> catch_mach_exception_raise\n#if defined(__arm64__) || defined(__aarch64__)\nchar* shellcode = \n\t\"\\x00\\x01\\x3f\\xd6\"\t\t//blr x8\n\t\"\\x00\\x00\\x00\\x14\"\t\t//b\t   //infinity loop, we will terminate this thread later\n\t\n\t//second thread\n\t\"\\x00\\x00\\x20\\xd4\"\t\t//brk 0\n\t\"\\x00\\x01\\x3f\\xd6\"\t\t//blr x8\n\t\"\\x00\\x00\\x20\\xd4\"\t\t//brk 0\n\t\"\\xc0\\x03\\x5f\\xd6\"\t\t//ret\n;\nint shellcode1_len = 8;\nint shellcode_length = 24;\n#else\n\nchar* shellcode = \n\t//\"\\x55\"\t\t\t\t//push   rbp\n\t//\"\\x48\\x89\\xE5\"\t\t//mov    rbp, rsp\n\t//\"\\x48\\x83\\xEC\\x10\"\t//sub    rsp, 0x10\n\t//\"\\x48\\x8D\\x7D\\xF8\"\t//lea    rdi, [rbp - 8]\n\t\"\\x90\"\t\t\t\t\t//nop\n\t\"\\x90\"\t\t\t\t\t//nop\n\t\"\\x90\"\t\t\t\t\t//nop\n\t\"\\xFF\\xD0\"\t\t\t\t//call   rax\n\t//\"\\x48\\x83\\xC4\\x10\"\t//add    rsp, 0x10\n\t//\"\\x5D\"\t\t\t\t//pop    rbp\n\t\"\\xeb\\xfe\"\t\t\t\t//jmp 0\t   //infinity loop, we will terminate this thread later\n\t\n\t//second thread\n\t\"\\xcc\"\t\t\t\t//int3\n\t//\"\\x55\"\t\t\t\t//push   rbp\n\t//\"\\x48\\x89\\xe5\"\t\t//mov  rbp, rsp\n\t\"\\xff\\xd0\" \t\t\t//call rax\n\t//\"\\x5D\" \t\t\t\t//pop    rbp\n\t\"\\xcc\"\t\t\t\t//int3\n\t\"\\xc3\"\t\t\t\t//ret\n;\nint shellcode1_len = 7;\nint shellcode_length = 12;\n#endif\nint injector__call_function(injector_t *injector, long *retval, long function_addr, ...)\n{\t\n\tva_list ap;\n\tva_start(ap, function_addr);\n\tlong arg1, arg2, arg3, arg4, arg5, arg6;\n    arg1 = va_arg(ap, long);\n    arg2 = va_arg(ap, long);\n    arg3 = va_arg(ap, long);\n    arg4 = va_arg(ap, long);\n    arg5 = va_arg(ap, long);\n    arg6 = va_arg(ap, long);\n\tva_end(ap);\n\tint rv;\n\n\tif(injector->shellcode_writed == 0){\n\t\tpcfmt_t pcfmt = (pcfmt_t)dlsym(RTLD_DEFAULT, \"pthread_create_from_mach_thread\");\n\n\t\t\n\t\trv = injector__write(injector, injector->code_addr, shellcode, shellcode_length);\n\t\tif(rv != 0){\n\t\t\treturn rv;\n\t\t}\n\t\tif(pcfmt == 0){\n\t\t\t//char* legacy_append = \n\t\t\t//\"\\xFF\\xD0\"\t\t//call rax\n\t\t\t//\"\\xcc\"\t\t\t//int3\n\t\t\t//;\n\t\t\t//rv = injector__write(injector, injector->code_addr, legacy_append, 3);\n\t\t\t\n\t\t\t//It turns out that we can call pthread_create in mach thread without _pthread_set_self on MacOS < 10.12\n\t\t\tpcfmt = (pcfmt_t)dlsym(RTLD_DEFAULT, \"pthread_create\");\n\t\t}\n\t\trv = injector__protect(injector, injector->code_addr, injector->code_size, FALSE, VM_PROT_READ | VM_PROT_EXECUTE);\n\t\tif (rv != 0) {\n\t\t\treturn rv;\n\t\t}\n\t\tinjector->shellcode_writed = 1;\n\t\tinjector->code2_addr = injector->code_addr + shellcode1_len;\n\t\t\n\t\tthread_act_t mach_thread;\n#if defined(__arm64__) || defined(__aarch64__)\n\t\tarm_thread_state64_t state;\n\t\tmemset(&state, '\\0', sizeof(state));\n\t\tstate.__pc = injector->code_addr;\n\t\tstate.__sp = injector->stack;\n\t\tstate.__x[8] = (uint64_t)pcfmt;\n\t\tstate.__x[0] = injector->stack - 32;\t\t\n\t\t\n\t\tstate.__x[1] = 0;\n\t\tstate.__x[2] = injector->code2_addr;\n\t\tstate.__x[3] = 0;\n\t\trv = thread_create_running(injector->remote_task, ARM_THREAD_STATE64, (thread_state_t)&state, ARM_THREAD_STATE64_COUNT , &mach_thread);\n#else\n\t\tx86_thread_state64_t state;\n\t\tmemset(&state, '\\0', sizeof(state));\n\t\tstate.__rip = injector->code_addr;\n\t\tstate.__rsp = injector->stack - 0x10;\n\t\tstate.__rbp = injector->stack;\t\n\t\tif(pcfmt == NULL){\n\t\t\tstate.__rax = (uint64_t)dlsym(RTLD_DEFAULT, \"_pthread_set_self\");\n\t\t\tstate.__rdi = 0;\n\t\t\tinjector->func_addr = (uint64_t)dlsym(RTLD_DEFAULT, \"pthread_create\");\n\t\t\tinjector->arg1 = injector->stack - 0x8;\n\t\t\tinjector->arg2 = 0;\n\t\t\tinjector->arg3 = injector->code2_addr;\n\t\t\tinjector->arg4 = 0;\n\t\t} else {\n\t\t\tstate.__rax = (uint64_t)pcfmt;\n\t\t\tstate.__rdi = injector->stack - 0x8;//&thread\n\t\t}\n\t\t\n\t\tstate.__rsi = 0;\n\t\tstate.__rdx = injector->code2_addr;\n\t\tstate.__rcx = 0;\t\t\n\n\t\trv = thread_create_running(injector->remote_task, x86_THREAD_STATE64, (thread_state_t)&state, x86_THREAD_STATE64_COUNT, &mach_thread);\n#endif\n\t\tif(rv != 0){\n\t\t\tinjector__set_errmsg(\"%s error : %s\", \"CREATE_THREAD\", mach_error_string(rv));\n\t\t\treturn INJERR_ERROR_IN_TARGET;\n\t\t}\n\t\tinjector->mach_thread = mach_thread;\n\t\tif(pcfmt == NULL){\n\t\t\tinjector->handle_action = TRAP_SETREGS;\n\t\t\tinjector__handle_exc(injector);\n\t\t}\n\t\tinjector->func_addr = function_addr;\n\t\tinjector->arg1 = arg1;\n\t\tinjector->arg2 = arg2;\n\t\tinjector->arg3 = arg3;\n\t\tinjector->arg4 = arg4;\n\t\tinjector->arg5 = arg5;\n\t\tinjector->arg6 = arg6;\n\t\n\t\tinjector->handle_action = TRAP_SETREGS;\n\t\tinjector__handle_exc(injector);\n\t} else {\n#if defined(__arm64__) || defined(__aarch64__)\n\n\t\tmach_msg_type_number_t state_count = ARM_THREAD_STATE64_COUNT;\n\t\tarm_thread_state64_t state;\n\t\trv = thread_get_state(injector->remote_thread, ARM_THREAD_STATE64, (thread_state_t)&state, &state_count);\n\t\tif(rv != 0){\n\t\t\tinjector__set_errmsg(\"%s error : %s\", \"THREAD_GET_STATE\", mach_error_string(rv));\n\t\t\treturn INJERR_ERROR_IN_TARGET;\n\t\t}\n\t\tstate.__pc = injector->code2_addr + 4;\n\t\tstate.__x[0] = arg1;\n\t\tstate.__x[1] = arg2;\n\t\tstate.__x[2] = arg3;\n\t\tstate.__x[3] = arg4;\n\t\tstate.__x[4] = arg5;\n\t\tstate.__x[5] = arg6;\n\t\tstate.__x[8] = function_addr;\n\t\trv = thread_set_state(injector->remote_thread, ARM_THREAD_STATE64, (thread_state_t)&state, ARM_THREAD_STATE64_COUNT);\n#else\n\t\tmach_msg_type_number_t state_count = x86_THREAD_STATE64_COUNT;\n\t\tx86_thread_state64_t state;\n\t\trv = thread_get_state(injector->remote_thread, x86_THREAD_STATE64, (thread_state_t)&state, &state_count);\n\t\tif(rv != 0){\n\t\t\tinjector__set_errmsg(\"%s error : %s\", \"THREAD_GET_STATE\", mach_error_string(rv));\n\t\t\treturn INJERR_ERROR_IN_TARGET;\n\t\t}\n\t\tstate.__rip = injector->code2_addr + 1;\n\t\tstate.__rax = function_addr;\n\t\tstate.__rdi = arg1;\n\t\tstate.__rsi = arg2;\n\t\tstate.__rdx = arg3;\n\t\tstate.__rcx = arg4;\n\t\tstate.__r8 = arg5;\n\t\tstate.__r9 = arg6;\n\t\trv = thread_set_state(injector->remote_thread, x86_THREAD_STATE64, (thread_state_t)&state, x86_THREAD_STATE64_COUNT);\n#endif\n\t\tif(rv != 0){\n\t\t\tinjector__set_errmsg(\"%s error : %s\", \"THREAD_SET_STATE\", mach_error_string(rv));\n\t\t\treturn INJERR_ERROR_IN_TARGET;\n\t\t}\n\t\trv = thread_resume(injector->remote_thread);\n\t\tif(rv != 0){\n\t\t\tinjector__set_errmsg(\"%s error : %s\", \"THREAD_RESUME\", mach_error_string(rv));\n\t\t\treturn INJERR_ERROR_IN_TARGET;\n\t\t}\n\t}\t\n\n\tinjector->handle_action = TRAP_GETREGS;\n\tinjector__handle_exc(injector);\n\tif(injector->handle_err != 0){\n\t\treturn injector->handle_err;\n\t}\n\t*retval = injector->retval;\n\treturn 0;\n}\n"
  },
  {
    "path": "src/macos/util.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2022 TheOiseth\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include \"injector_internal.h\"\n#include <stdarg.h>\n#include <libproc.h>\n#include <bsm/libbsm.h>\n#include <sys/sysctl.h>\n#include <sys/types.h>\n#include <unistd.h>\n\n\nchar injector__errmsg[512];\nchar injector__errmsg_is_set;\n\nvoid injector__set_errmsg(const char *format, ...)\n{\n    va_list ap;\n    int rv;\n\n    /* prevent the error message from being overwritten. */\n    if (injector__errmsg_is_set) {\n        return;\n    }\n    injector__errmsg_is_set = 1;\n\n    va_start(ap, format);\n    rv = vsnprintf(injector__errmsg, sizeof(injector__errmsg), format, ap);\n    va_end(ap);\n    if (rv == -1 || rv >= sizeof(injector__errmsg)) {\n        injector__errmsg[sizeof(injector__errmsg) - 1] = '\\0';\n    }\n}\n#ifndef P_TRANSLATED\n#define P_TRANSLATED    0x00020000\n#endif\nint injector__get_process_arch(pid_t pid, arch_t *arch){\n    int mib[CTL_MAXNAME] = {0};\n    mib[0] = CTL_KERN;\n    mib[1] = KERN_PROC;\n    mib[2] = KERN_PROC_PID;\n    mib[3] = pid;\n    size_t length = 4;\n    struct kinfo_proc proc_info = {0};\n    size_t size = sizeof(proc_info);\n\n    if(sysctl(mib, (u_int)length, &proc_info, &size, NULL, 0) != 0) {\n        *arch = ARCH_UNKNOWN;\n        return INJERR_SUCCESS;\n    }\n    if (size == 0) {\n        injector__set_errmsg(\"Process %d not found\", pid);\n        return INJERR_NO_PROCESS;\n    }\n\n    if(P_TRANSLATED == (P_TRANSLATED & proc_info.kp_proc.p_flag)){\n        if(P_LP64 == (P_LP64 & proc_info.kp_proc.p_flag)){\n            *arch = ARCH_X86_64;\n            return INJERR_SUCCESS;\n        } else {\n            *arch = ARCH_I386;\n            return INJERR_SUCCESS;\n        }\n    } else {\n        arch_t sys_arch = injector__get_system_arch();\n        if(sys_arch == ARCH_ARM64){\n            *arch = ARCH_ARM64;\n            return INJERR_SUCCESS;\n        }\n#if defined(__arm64__) || defined(__aarch64__)\n        if(sys_arch == ARCH_UNKNOWN){\n            *arch = ARCH_ARM64;\n            return INJERR_SUCCESS;\n        }\n#endif\n    }\n\n    if(P_LP64 == (P_LP64 & proc_info.kp_proc.p_flag)){\n        *arch = ARCH_X86_64;\n        return INJERR_SUCCESS;\n    }\n    *arch = ARCH_I386;\n    return INJERR_SUCCESS;\n}\n\n#ifndef CPU_TYPE_ARM64\n#define CPU_TYPE_ARM            ((cpu_type_t) 12)\n#define CPU_ARCH_ABI64          0x01000000\n#define CPU_TYPE_ARM64          (CPU_TYPE_ARM | CPU_ARCH_ABI64)\n#endif\narch_t injector__get_system_arch(){\n\tsize_t size;\n\tcpu_type_t type = -1;\n\tint mib[CTL_MAXNAME] = {0};\n\tsize_t length = CTL_MAXNAME;\n\n\tif (sysctlnametomib(\"sysctl.proc_cputype\", mib, &length) != 0){\n\t\treturn ARCH_UNKNOWN;\n\t}\n\n\tmib[length] = getpid();\n\tlength++;\n\tsize = sizeof(cpu_type_t);\n\n\tif (sysctl(mib, (u_int)length, &type, &size, 0, 0) != 0){\n\t\treturn ARCH_UNKNOWN;\n\t}\n\tif (CPU_TYPE_X86_64 == type) {\n\t\treturn ARCH_X86_64;\n\t}\n\n\tif (CPU_TYPE_ARM64 == type) {\n\t\treturn ARCH_ARM64;\n\t}\n\treturn ARCH_UNKNOWN;\n}\nconst char *injector__arch2name(arch_t arch)\n{\n    switch (arch) {\n    case ARCH_X86_64:\n        return \"x86_64\";\n    case ARCH_I386:\n        return \"i386\";\n    case ARCH_ARM64:\n        return \"ARM64\";\n    case ARCH_POWERPC_64:\n        return \"PowerPC 64-bit\";\n    case ARCH_POWERPC:\n        return \"PowerPC\";\n\tcase ARCH_UNKNOWN:\n        return \"Unknown\";\n    }\n    return \"?\";\n}"
  },
  {
    "path": "src/windows/GNUmakefile",
    "content": "INJECTOR_OBJS = injector.o\nCFLAGS = -I../../include\n\nall: injector.dll injector-static.lib\n\ninjector.dll: $(INJECTOR_OBJS)\n\t$(CC) -shared -o $@ $(INJECTOR_OBJS) $(CFLAGS) -Wl,--out-implib,injector.lib -ldbghelp\n\ninjector-static.lib: $(INJECTOR_OBJS)\n\t$(RM) $@\n\t$(AR) rcs -o $@ $(INJECTOR_OBJS)\n\nclean:\n\t$(RM) injector.dll injector.lib injector-static.lib $(INJECTOR_OBJS)\n\n"
  },
  {
    "path": "src/windows/Makefile.win32",
    "content": "# -*- Makefile -*-\nCFLAGS = -nologo -O2 -I../../include\n\nRTFLAG = -MD  # link with dynamic runtime library\n# RTFLAG = -MT  # link with static runtime library\n\nLINKFLAGS = -nologo\n\nRELEASE_DLL = injector.dll\nDEBUG_DLL = injectord.dll\nRELEASE_STATIC_LIB = injector-static.lib\nDEBUG_STATIC_LIB = injectord-static.lib\n\nRELEASE_OBJS = injector.obj\nDEBUG_OBJS = injectord.obj\n\nTARGETS = $(RELEASE_DLL) $(DEBUG_DLL) $(RELEASE_STATIC_LIB) $(DEBUG_STATIC_LIB)\n\n!IF \"$(ARM64EC)\" != \"\"\nCFLAGS = $(CFLAGS) -arm64EC\nLINKFLAGS = $(LINKFLAGS) -machine:arm64ec\n!ENDIF\n\nall: $(TARGETS)\n\ninjector.obj: injector.c\n\t$(CC) $(CFLAGS) $(RTFLAG) -c /Foinjector.obj injector.c\n\ninjectord.obj: injector.c\n\t$(CC) $(CFLAGS) $(RTFLAG)d -c /Foinjectord.obj injector.c\n\ninjector.dll: $(RELEASE_OBJS)\n\tlink $(LINKFLAGS) /DLL /DEF:injector.def /OUT:injector.dll $(RELEASE_OBJS)\n\ninjectord.dll: $(DEBUG_OBJS)\n\tlink $(LINKFLAGS) /DLL /DEF:injector.def /OUT:injectord.dll $(DEBUG_OBJS)\n\ninjector-static.lib: $(RELEASE_OBJS)\n\tlib $(LINKFLAGS) /OUT:injector-static.lib $(RELEASE_OBJS)\n\ninjectord-static.lib: $(DEBUG_OBJS)\n\tlib $(LINKFLAGS) /OUT:injectord-static.lib $(DEBUG_OBJS)\n\nclean:\n\tdel $(TARGETS) $(RELEASE_OBJS) $(DEBUG_OBJS) injector.lib injectord.lib injector.exp injectord.exp\n"
  },
  {
    "path": "src/windows/injector.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2018-2023 Kubo Takehiro <kubo@jiubao.org>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#ifndef _WIN32_WINNT\n#define _WIN32_WINNT 0x0602\n#endif\n#ifndef _CRT_SECURE_NO_WARNINGS\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n#include <stdio.h>\n#include <stdint.h>\n#include <stdarg.h>\n#include <malloc.h>\n#include <windows.h>\n#include <psapi.h>\n#include <dbghelp.h>\n#include <tlhelp32.h>\n#include \"injector.h\"\n\n#if !defined(WDK_NTDDI_VERSION) || WDK_NTDDI_VERSION < 0x0A00000B\n// Windows SDK version < 10.0.22000.0\n#define ProcessMachineTypeInfo 9\ntypedef enum _MACHINE_ATTRIBUTES {\n    UserEnabled    = 0x00000001,\n    KernelEnabled  = 0x00000002,\n    Wow64Container = 0x00000004\n} MACHINE_ATTRIBUTES;\ntypedef struct _PROCESS_MACHINE_INFORMATION {\n    USHORT ProcessMachine;\n    USHORT Res0;\n    MACHINE_ATTRIBUTES MachineAttributes;\n} PROCESS_MACHINE_INFORMATION;\n#endif\n\n#pragma comment(lib, \"advapi32.lib\")\n#pragma comment(lib, \"dbghelp.lib\")\n#if !defined(PSAPI_VERSION) || PSAPI_VERSION == 1\n#pragma comment(lib, \"psapi.lib\")\n#endif\n\ntypedef BOOL (WINAPI *IsWow64Process2_t)(HANDLE hProcess, USHORT *pProcessMachine, USHORT *pNativeMachine);\ntypedef BOOL (WINAPI *GetProcessInformation_t)(HANDLE hProcess, PROCESS_INFORMATION_CLASS ProcessInformationClass, LPVOID ProcessInformation, DWORD ProcessInformationSize);\n\nstatic DWORD page_size = 0;\nstatic size_t func_LoadLibraryW;\nstatic size_t func_FreeLibrary;\nstatic size_t func_GetLastError;\nstatic size_t func_GetProcAddress;\nstatic char errmsg[512];\n\ntypedef struct {\n    uint64_t func;\n    uint64_t arg1;\n    uint64_t arg2;\n    uint64_t arg3;\n    uint64_t arg4;\n    uint64_t arg5;\n    uint64_t arg6;\n} remote_call_args_t;\n\n// size_t remote_call(remote_call_args_t *args)\n// {\n//    size_t rv = args->func(args->arg1, args->arg2, args->arg3, args->arg4, args->arg5, args->arg6);\n//    *(DWORD*)args = GetLastError();\n//    return rv;\n// }\nstatic const char x64_code_template[] =\n\n    /* 0000: */ \"\\x40\\x53\"                 // push rbx\n    /* 0002: */ \"\\x48\\x8B\\xD9\"             // mov  rbx,rcx   ; preserve the first argument\n    /* 0005: */ \"\\x48\\x83\\xEC\\x30\"         // sub  rsp,30h   ; align the stack pointer\n    /* 0009: */ \"\\x48\\x8B\\x41\\x30\"         // mov  rax,qword ptr [rcx+30h] ; set the 6th argument\n    /* 000D: */ \"\\x48\\x89\\x44\\x24\\x28\"     // mov  qword ptr [rsp+28h],rax ;   ditto\n    /* 0012: */ \"\\x48\\x8B\\x41\\x28\"         // mov  rax,qword ptr [rcx+28h] ; set the 5th argument\n    /* 0016: */ \"\\x48\\x89\\x44\\x24\\x20\"     // mov  qword ptr [rsp+20h],rax ;   ditto\n    /* 001B: */ \"\\x4C\\x8B\\x49\\x20\"         // mov  r9,qword ptr [rcx+20h]  ; set the 4th argument\n    /* 001F: */ \"\\x4C\\x8B\\x41\\x18\"         // mov  r8,qword ptr [rcx+18h]  ; set the 3rd argument\n    /* 0023: */ \"\\x48\\x8B\\x51\\x10\"         // mov  rdx,qword ptr [rcx+10h] ; set the 2nd argument\n    /* 0027: */ \"\\x48\\x8B\\x49\\x08\"         // mov  rcx,qword ptr [rcx+8]   ; set the 1st argument\n    /* 002B: */ \"\\xFF\\x13\"                 // call qword ptr [rbx]         ; call func\n    /* 002D: */ \"\\x48\\x89\\x03\"             // mov  qword ptr [rbx],rax     ; store the return value\n    /* 0030: */ \"\\xFF\\x15\\x0A\\x00\\x00\\x00\" // call GetLastError\n    /* 0036: */ \"\\x48\\x83\\xC4\\x30\"         // add  rsp,30h\n    /* 003A: */ \"\\x5B\"                     // pop  rbx\n    /* 003B: */ \"\\xC3\"                     // ret\n    /* 003C: */ \"\\x90\\x90\\x90\\x90\"         // nop; nop; nop; nop\n#define X64_ADDR_GetLastError  0x0040\n    /* 0040: */ \"\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\"\n    ;\n#define X64_CODE_SIZE          0x0048\n\nstatic const uint32_t arm64_code_template[] = {\n    /* 0000: */ 0xa9be7bfd, // stp x29, x30, [sp, #-32]! ; prolog\n    /* 0004: */ 0x910003fd, // mov x29, sp               ; ditto\n    /* 0008: */ 0xf9000bf3, // str x19, [sp, #16]        ; reserve x19\n    /* 000c: */ 0xaa0003f3, // mov x19, x0               ; set args to x19\n    /* 0010: */ 0xa9429664, // ldp x4, x5, [x19, #40]    ; set 5th and 6th arguments\n    /* 0014: */ 0xa9418e62, // ldp x2, x3, [x19, #24]    ; set 3rd and 4th arguments\n    /* 0018: */ 0xa9408660, // ldp x0, x1, [x19, #8]     ; set 1st and 2nd arguments\n    /* 001c: */ 0xf9400269, // ldr x9, [x19]             ; get args->func\n    /* 0020: */ 0xd63f0120, // blr x9                    ; call args->func\n    /* 0024: */ 0xf9000260, // str x0, [x19]             ; set the return value\n    /* 0028: */ 0xf9400bf3, // ldr x19, [sp, #16]        ; restore x19\n    /* 002c: */ 0xa8c27bfd, // ldp x29, x30, [sp], #32   ; epilog\n    /* 0030: */ 0x58000049, // ldr x9, ARM64_ADDR_GetLastError\n    /* 0034: */ 0xd61f0120, // br  x9\n#define ARM64_ADDR_GetLastError    0x0038\n    /* 0038: */ 0,\n    /* 003c: */ 0,\n};\n#define ARM64_CODE_SIZE          0x0040\n\nstatic const uint16_t armt_code_template[] = {\n    /* 0000: */ 0xb530, // push {r4, r5, lr}   ; prolog\n    /* 0002: */ 0xb083, // sub  sp, #12        ; reserve stack for arguments\n    /* 0004: */ 0x0004, // movs r4, r0\n    /* 0006: */ 0x6b25, // ldr  r5, [r4, #48]  ; set the 6th argument\n    /* 0008: */ 0x9501, // str  r5, [sp, #4]   ;   ditto\n    /* 000a: */ 0x6aa5, // ldr  r5, [r4, #40]  ; set the 5th argument\n    /* 000c: */ 0x9500, // str  r5, [sp, #0]   ;   ditto\n    /* 000e: */ 0x6a23, // ldr  r3, [r4, #32]  ; set the 4th argument\n    /* 0010: */ 0x69a2, // ldr  r2, [r4, #24]  ; set the 3rd argument\n    /* 0012: */ 0x6921, // ldr  r1, [r4, #16]   ; set the 2nd argument\n    /* 0014: */ 0x68a0, // ldr  r0, [r4, #8]   ; set the 1st argument\n    /* 0016: */ 0x6825, // ldr  r5, [r4, #0]   ; get args->func\n    /* 0018: */ 0x47a8, // blx  r5             ; call args->func\n    /* 001a: */ 0x6020, // str  r0, [r4, #0]   ; set the return value\n    /* 001c: */ 0x4d01, // ldr  r5, [pc, #4]   ; get the address of GetLastError (0x0024)\n    /* 001e: */ 0x47a8, // blx  r5             ; call GetLastError\n    /* 0020: */ 0xb003, // add  sp, #12        ; restore stack\n    /* 0022: */ 0xbd30, // pop  {r4, r5, pc}   ; epilog\n#define ARMT_ADDR_GetLastError    0x0024\n    /* 0024: */ 0,      // .word\n    /* 0026: */ 0,      // .word\n};\n#define ARMT_CODE_SIZE          0x0028\n\nstatic const char x86_code_template[] =\n    /* 0000: */ \"\\x55\"                 // push ebp\n    /* 0001: */ \"\\x8B\\xEC\"             // mov  ebp,esp\n    /* 0003: */ \"\\x53\"                 // push ebx\n    /* 0004: */ \"\\x8B\\x5D\\x08\"         // mov  ebx,dword ptr [ebp+8] ; get args\n    /* 0007: */ \"\\xFF\\x73\\x30\"         // push dword ptr [ebx+30h]   ; set the 6th argument\n    /* 000A: */ \"\\xFF\\x73\\x28\"         // push dword ptr [ebx+28h]   ; set the 5th argument\n    /* 000D: */ \"\\xFF\\x73\\x20\"         // push dword ptr [ebx+20h]   ; set the 4th argument\n    /* 0010: */ \"\\xFF\\x73\\x18\"         // push dword ptr [ebx+18h]   ; set the 3rd argument\n    /* 0013: */ \"\\xFF\\x73\\x10\"         // push dword ptr [ebx+10h]     ; set the 2nd argument\n    /* 0016: */ \"\\xFF\\x73\\x08\"         // push dword ptr [ebx+8]     ; set the 1st argument\n    /* 0019: */ \"\\xFF\\x13\"             // call dword ptr [ebx]       ; call args->func\n    /* 001B: */ \"\\x89\\x03\"             // mov  dword ptr [ebx],eax   ; store the return value\n#define X86_CALL_GetLastError   0x001D\n    /* 001D: */ \"\\xE8\\x00\\x00\\x00\\x00\" // call GetLastError\n    /* 0022: */ \"\\x8B\\x5D\\xF8\"         // mov  ebx,dword ptr [ebp-8]\n    /* 0025: */ \"\\xC9\"                 // leave\n    /* 0026: */ \"\\xC2\\x04\\x00\"         // ret  4\n    ;\n\n#define X86_CODE_SIZE          0x0029\n\n#ifdef _M_AMD64\n#define CURRENT_ARCH \"x64\"\n#define CURRENT_IMAGE_FILE_MACHINE IMAGE_FILE_MACHINE_AMD64\n#endif\n#ifdef _M_ARM64\n#define CURRENT_ARCH \"arm64\"\n#define CURRENT_IMAGE_FILE_MACHINE IMAGE_FILE_MACHINE_ARM64\n#endif\n#ifdef _M_ARMT\n#define CURRENT_ARCH \"arm\"\n#define CURRENT_IMAGE_FILE_MACHINE IMAGE_FILE_MACHINE_ARMNT\n#endif\n#ifdef _M_IX86\n#define CURRENT_ARCH \"x86\"\n#define CURRENT_IMAGE_FILE_MACHINE IMAGE_FILE_MACHINE_I386\n#endif\n\n#define CODE_SIZE __max(__max(X64_CODE_SIZE, ARM64_CODE_SIZE), __max(X86_CODE_SIZE, ARMT_CODE_SIZE))\n\nstatic BOOL CallIsWow64Process2(HANDLE hProcess, USHORT *pProcessMachine, USHORT *pNativeMachine)\n{\n    static IsWow64Process2_t IsWow64Process2_func = (IsWow64Process2_t)-1;\n    if (IsWow64Process2_func == (IsWow64Process2_t)-1) {\n        IsWow64Process2_func = (IsWow64Process2_t)GetProcAddress(GetModuleHandleA(\"kernel32\"), \"IsWow64Process2\");\n    }\n    if (IsWow64Process2_func == NULL) {\n       return FALSE;\n    }\n    return IsWow64Process2_func(hProcess, pProcessMachine, pNativeMachine);\n}\n#define IsWow64Process2 CallIsWow64Process2\n\nstatic BOOL CallGetProcessInformation(HANDLE hProcess, PROCESS_INFORMATION_CLASS ProcessInformationClass, LPVOID ProcessInformation, DWORD ProcessInformationSize)\n{\n    static GetProcessInformation_t GetProcessInformation_func = (GetProcessInformation_t)-1;\n    if (GetProcessInformation_func == (GetProcessInformation_t)-1) {\n        GetProcessInformation_func = (GetProcessInformation_t)GetProcAddress(GetModuleHandleA(\"kernel32\"), \"GetProcessInformation\");\n    }\n    if (GetProcessInformation_func == NULL) {\n       return FALSE;\n    }\n    return GetProcessInformation_func(hProcess, ProcessInformationClass, ProcessInformation, ProcessInformationSize);\n}\n#define GetProcessInformation CallGetProcessInformation\n\nstatic void set_errmsg(const char *format, ...);\nstatic const char *w32strerr(DWORD err);\nstatic USHORT process_arch(HANDLE hProcess);\nstatic const char *arch_name(USHORT arch);\n\nstruct injector {\n    HANDLE hProcess;\n    USHORT arch;\n    char *code;\n    char *data;\n    size_t load_library;\n    size_t free_library;\n    size_t get_last_error;\n    size_t get_proc_address;\n};\n\nstatic BOOL init(void)\n{\n    SYSTEM_INFO si;\n    HANDLE hToken;\n    LUID luid;\n    TOKEN_PRIVILEGES tp;\n    HMODULE kernel32 = GetModuleHandleA(\"kernel32\");\n\n    GetSystemInfo(&si);\n    page_size = si.dwPageSize;\n    func_LoadLibraryW = (size_t)GetProcAddress(kernel32, \"LoadLibraryW\");\n    func_FreeLibrary = (size_t)GetProcAddress(kernel32, \"FreeLibrary\");\n    func_GetProcAddress = (size_t)GetProcAddress(kernel32, \"GetProcAddress\");\n    func_GetLastError = (size_t)GetProcAddress(kernel32, \"GetLastError\");\n\n    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) {\n        return FALSE;\n    }\n    if (!LookupPrivilegeValue(0, SE_DEBUG_NAME, &luid)) {\n        CloseHandle(hToken);\n        return FALSE;\n    }\n    tp.PrivilegeCount = 1;\n    tp.Privileges[0].Luid = luid;\n    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\n    if (!AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL)) {\n        CloseHandle(hToken);\n        return FALSE;\n    }\n    CloseHandle(hToken);\n    return TRUE;\n}\n\nstatic DWORD name_index(IMAGE_NT_HEADERS *nt_hdrs, void *base, const DWORD *names, DWORD num_names, const char *name)\n{\n    DWORD idx;\n    for (idx = 0; idx < num_names; idx++) {\n        if (strcmp((const char*)ImageRvaToVa(nt_hdrs, base, names[idx], NULL), name) == 0) {\n            return idx;\n        }\n    }\n    set_errmsg(\"Could not find the address of %s\", name);\n    return (DWORD)-1;\n}\n\nstatic int funcaddr(DWORD pid, injector_t *injector)\n{\n    HANDLE hSnapshot;\n    MODULEENTRY32W me;\n    BOOL ok;\n    HANDLE hFile = INVALID_HANDLE_VALUE;\n    HANDLE hFileMapping = NULL;\n    void *base = NULL;\n    IMAGE_NT_HEADERS *nt_hdrs;\n    ULONG exp_size;\n    const IMAGE_EXPORT_DIRECTORY *exp;\n    const DWORD *names, *funcs;\n    const WORD *ordinals;\n    DWORD idx;\n    int rv = INJERR_OTHER;\n\n    /* Get the full path of kernel32.dll. */\nretry:\n    hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);\n    if (hSnapshot == INVALID_HANDLE_VALUE) {\n        DWORD err = GetLastError();\n        switch (err) {\n        case ERROR_BAD_LENGTH:\n            goto retry;\n        case ERROR_ACCESS_DENIED:\n            rv = INJERR_PERMISSION;\n            break;\n        case ERROR_INVALID_PARAMETER:\n            rv = INJERR_NO_PROCESS;\n            break;\n        default:\n            rv = INJERR_OTHER;\n        }\n        set_errmsg(\"CreateToolhelp32Snapshot error: %s\", w32strerr(err));\n        return rv;\n    }\n    me.dwSize = sizeof(me);\n    for (ok = Module32FirstW(hSnapshot, &me); ok; ok = Module32NextW(hSnapshot, &me)) {\n        if (wcsicmp(me.szModule, L\"kernel32.dll\") == 0) {\n            break;\n        }\n    }\n    CloseHandle(hSnapshot);\n    if (!ok) {\n        set_errmsg(\"kernel32.dll could not be found.\");\n        return INJERR_OTHER;\n    }\n\n    /* Get the export directory in the kernel32.dll. */\n    hFile = CreateFileW(me.szExePath, GENERIC_READ, FILE_SHARE_READ, NULL,\n                        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n    if (hFile == INVALID_HANDLE_VALUE) {\n        set_errmsg(\"failed to open file %s: %s\", me.szExePath, w32strerr(GetLastError()));\n        goto exit;\n    }\n    hFileMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);\n    if (hFileMapping == NULL) {\n        set_errmsg(\"failed to create file mapping of %s: %s\", me.szExePath, w32strerr(GetLastError()));\n        goto exit;\n    }\n    base = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);\n    if (base == NULL) {\n        set_errmsg(\"failed to map file %s to memory: %s\", me.szExePath, w32strerr(GetLastError()));\n        goto exit;\n    }\n    nt_hdrs = ImageNtHeader(base);\n    if (nt_hdrs == NULL) {\n        set_errmsg(\"ImageNtHeader error: %s\", w32strerr(GetLastError()));\n        goto exit;\n    }\n    exp = (const IMAGE_EXPORT_DIRECTORY *)ImageDirectoryEntryToDataEx(base, FALSE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size, NULL);\n    if (exp == NULL) {\n        set_errmsg(\"ImageDirectoryEntryToDataEx error: %s\", w32strerr(GetLastError()));\n        goto exit;\n    }\n    if (exp->NumberOfNames == 0) {\n        set_errmsg(\"No export entires are not found.\");\n        goto exit;\n    }\n    names = (const DWORD*)ImageRvaToVa(nt_hdrs, base, exp->AddressOfNames, NULL);\n    if (names == NULL) {\n        set_errmsg(\"ImageRvaToVa error: %s\", w32strerr(GetLastError()));\n        goto exit;\n    }\n    ordinals = (const WORD*)ImageRvaToVa(nt_hdrs, base, exp->AddressOfNameOrdinals, NULL);\n    if (ordinals == NULL) {\n        set_errmsg(\"ImageRvaToVa error: %s\", w32strerr(GetLastError()));\n        goto exit;\n    }\n    funcs = (const DWORD*)ImageRvaToVa(nt_hdrs, base, exp->AddressOfFunctions, NULL);\n    if (funcs == NULL) {\n        set_errmsg(\"ImageRvaToVa error: %s\", w32strerr(GetLastError()));\n        goto exit;\n    }\n\n    /* Find the address of LoadLibraryW */\n    idx = name_index(nt_hdrs, base, names, exp->NumberOfNames, \"LoadLibraryW\");\n    if (idx == (DWORD)-1) {\n        goto exit;\n    }\n    injector->load_library = (size_t)me.modBaseAddr + funcs[ordinals[idx]];\n\n    /* Find the address of FreeLibrary */\n    idx = name_index(nt_hdrs, base, names, exp->NumberOfNames, \"FreeLibrary\");\n    if (idx == (DWORD)-1) {\n        goto exit;\n    }\n    injector->free_library = (size_t)me.modBaseAddr + funcs[ordinals[idx]];\n\n    /* Find the address of GetProcAddress */\n    idx = name_index(nt_hdrs, base, names, exp->NumberOfNames, \"GetProcAddress\");\n    if (idx == (DWORD)-1) {\n        goto exit;\n    }\n    injector->get_proc_address = (size_t)me.modBaseAddr + funcs[ordinals[idx]];\n\n    /* Find the address of GetLastError */\n    idx = name_index(nt_hdrs, base, names, exp->NumberOfNames, \"GetLastError\");\n    if (idx == (DWORD)-1) {\n        goto exit;\n    }\n    injector->get_last_error = (size_t)me.modBaseAddr + funcs[ordinals[idx]];\n    rv = 0;\nexit:\n    if (base != NULL) {\n        UnmapViewOfFile(base);\n    }\n    if (hFileMapping != NULL) {\n        CloseHandle(hFileMapping);\n    }\n    if (hFile != INVALID_HANDLE_VALUE) {\n        CloseHandle(hFile);\n    }\n    return rv;\n}\n\nstatic int remote_call(injector_t *injector, remote_call_args_t *args, size_t size, intptr_t *retval, DWORD *last_error)\n{\n    char *code = injector->code;\n    HANDLE hThread;\n    SIZE_T sz;\n\n    if (injector->arch == IMAGE_FILE_MACHINE_ARMNT) {\n        ++code;\n    }\n    if (!WriteProcessMemory(injector->hProcess, injector->data, args, size, &sz)) {\n        set_errmsg(\"WriteProcessMemory error: %s\", w32strerr(GetLastError()));\n        return INJERR_OTHER;\n    }\n    hThread = CreateRemoteThread(injector->hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)code, injector->data, 0, NULL);\n    if (hThread == NULL) {\n        set_errmsg(\"CreateRemoteThread error: %s\", w32strerr(GetLastError()));\n        return INJERR_OTHER;\n    }\n    WaitForSingleObject(hThread, INFINITE);\n    if (last_error) {\n        GetExitCodeThread(hThread, last_error);\n    }\n    CloseHandle(hThread);\n    if (retval) {\n        union {\n            size_t s;\n            uint32_t u32;\n        } val;\n        size_t valsize = sizeof(size_t);\n        switch (injector->arch) {\n          case IMAGE_FILE_MACHINE_ARMNT:\n          case IMAGE_FILE_MACHINE_I386:\n              valsize = 4;\n              break;\n        }\n        if (!ReadProcessMemory(injector->hProcess, injector->data, &val, valsize, &sz)) {\n            set_errmsg(\"ReadProcessMemory error: %s\", w32strerr(GetLastError()));\n            return INJERR_OTHER;\n        }\n        if (valsize == 4) {\n            *retval = val.u32;\n        } else {\n            *retval = val.s;\n        }\n    }\n    return 0;\n}\n\nint injector_attach(injector_t **injector_out, DWORD pid)\n{\n    injector_t *injector;\n    DWORD dwDesiredAccess =\n        PROCESS_QUERY_LIMITED_INFORMATION | /* for IsWow64Process() */\n        PROCESS_CREATE_THREAD |  /* for CreateRemoteThread() */\n        PROCESS_VM_OPERATION  |  /* for VirtualAllocEx() */\n        PROCESS_VM_READ       |  /* for ReadProcessMemory() */\n        PROCESS_VM_WRITE;        /* for WriteProcessMemory() */\n    DWORD old_protect;\n    SIZE_T written;\n    int rv;\n    char code[CODE_SIZE];\n    size_t code_size;\n\n    if (page_size == 0) {\n        init();\n    }\n\n    injector = calloc(1, sizeof(injector_t));\n    if (injector == NULL) {\n        set_errmsg(\"malloc error: %s\", strerror(errno));\n        return INJERR_NO_MEMORY;\n    }\n    injector->hProcess = OpenProcess(dwDesiredAccess, FALSE, pid);\n    if (injector->hProcess == NULL) {\n        DWORD err = GetLastError();\n        set_errmsg(\"OpenProcess error: %s\", w32strerr(err));\n        switch (err) {\n        case ERROR_ACCESS_DENIED:\n            rv = INJERR_PERMISSION;\n            break;\n        case ERROR_INVALID_PARAMETER:\n            rv = INJERR_NO_PROCESS;\n            break;\n        default:\n            rv = INJERR_OTHER;\n        }\n        goto error_exit;\n    }\n    injector->load_library = func_LoadLibraryW;\n    injector->free_library = func_FreeLibrary;\n    injector->get_last_error = func_GetLastError;\n    injector->get_proc_address = func_GetProcAddress;\n\n    injector->arch = process_arch(injector->hProcess);\n    switch (injector->arch) {\n#if defined(_M_ARM64) // arm64\n    case IMAGE_FILE_MACHINE_ARM64:\n    case IMAGE_FILE_MACHINE_ARMNT:\n        break;\n#endif\n#if defined(_M_AMD64) // x64\n        static USHORT native_machine = IMAGE_FILE_MACHINE_UNKNOWN;\n    case IMAGE_FILE_MACHINE_AMD64:\n        break;\n    case IMAGE_FILE_MACHINE_I386:\n        if (native_machine == IMAGE_FILE_MACHINE_UNKNOWN) {\n            USHORT dummy;\n            if (!IsWow64Process2(GetCurrentProcess(), &dummy, &native_machine)) {\n                native_machine = IMAGE_FILE_MACHINE_AMD64;\n            }\n        }\n        if (native_machine == IMAGE_FILE_MACHINE_AMD64) {\n            // x86 process on Windows x64\n            break;\n        }\n        // x86 process on Windows arm64\n        // FALL THROUGH\n#endif\n#if defined(_M_IX86) // x86\n    case IMAGE_FILE_MACHINE_I386:\n        break;\n#endif\n#if defined(_M_ARMT) // arm32\n    case IMAGE_FILE_MACHINE_ARMNT:\n        break;\n#endif\n    default:\n        set_errmsg(\"%s target process isn't supported by %s process.\",\n                   arch_name(injector->arch), CURRENT_ARCH);\n        rv = INJERR_UNSUPPORTED_TARGET;\n        goto error_exit;\n    }\n\n    if (injector->arch != CURRENT_IMAGE_FILE_MACHINE) {\n        rv = funcaddr(pid, injector);\n        if (rv != 0) {\n            goto error_exit;\n        }\n    }\n\n    injector->code = VirtualAllocEx(injector->hProcess, NULL, 2 * page_size,\n                                          MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READ);\n    if (injector->code == NULL) {\n        set_errmsg(\"VirtualAllocEx error: %s\", w32strerr(GetLastError()));\n        rv = INJERR_OTHER;\n        goto error_exit;\n    }\n    injector->data = injector->code + page_size;\n    switch (injector->arch) {\n    case IMAGE_FILE_MACHINE_AMD64: /* x64 */\n        memcpy(code, x64_code_template, X64_CODE_SIZE);\n        code_size = X64_CODE_SIZE;\n        *(size_t*)(code + X64_ADDR_GetLastError) = injector->get_last_error;\n        break;\n    case IMAGE_FILE_MACHINE_ARM64: /* arm64 */\n        memcpy(code, arm64_code_template, ARM64_CODE_SIZE);\n        code_size = ARM64_CODE_SIZE;\n        *(size_t*)(code + ARM64_ADDR_GetLastError) = injector->get_last_error;\n        break;\n    case IMAGE_FILE_MACHINE_ARMNT: /* arm (thumb mode) */\n        memcpy(code, armt_code_template, ARMT_CODE_SIZE);\n        code_size = ARMT_CODE_SIZE;\n        *(uint32_t*)(code + ARMT_ADDR_GetLastError) = (uint32_t)injector->get_last_error;\n        break;\n    case IMAGE_FILE_MACHINE_I386: /* x86 */\n        memcpy(code, x86_code_template, X86_CODE_SIZE);\n        code_size = X86_CODE_SIZE;\n#define FIX_CALL_RELATIVE(addr, offset) *(uint32_t*)(code + offset + 1) = addr - ((uint32_t)(size_t)injector->code + offset + 5)\n        FIX_CALL_RELATIVE(injector->get_last_error, X86_CALL_GetLastError);\n        break;\n    default:\n        set_errmsg(\"Never reach here: arch=0x%x\", injector->arch);\n        rv = INJERR_OTHER;\n        goto error_exit;\n    }\n\n    if (!WriteProcessMemory(injector->hProcess, injector->code, code, code_size, &written)) {\n        set_errmsg(\"WriteProcessMemory error: %s\", w32strerr(GetLastError()));\n        rv = INJERR_OTHER;\n        goto error_exit;\n    }\n\n    if (!VirtualProtectEx(injector->hProcess, injector->data, page_size, PAGE_READWRITE, &old_protect)) {\n        set_errmsg(\"VirtualProtectEx error: %s\", w32strerr(GetLastError()));\n        rv = INJERR_OTHER;\n        goto error_exit;\n    }\n\n    *injector_out = injector;\n    return 0;\nerror_exit:\n    injector_detach(injector);\n    return rv;\n}\n\nint injector_inject(injector_t *injector, const char *path, void **handle)\n{\n    DWORD pathlen = (DWORD)strlen(path);\n    wchar_t *wpath;\n    DWORD wpathlen;\n\n    if (pathlen == 0) {\n        set_errmsg(\"The specified path is empty.\");\n        return INJERR_FILE_NOT_FOUND;\n    }\n    if (pathlen > MAX_PATH) {\n        set_errmsg(\"too long file path: %s\", path);\n        return INJERR_FILE_NOT_FOUND;\n    }\n\n    wpath = _alloca((pathlen + 1) * sizeof(wchar_t));\n    wpathlen = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, path, pathlen, wpath, pathlen + 1);\n    wpath[wpathlen] = L'\\0';\n    return injector_inject_w(injector, wpath, handle);\n}\n\nint injector_inject_w(injector_t *injector, const wchar_t *path, void **handle)\n{\n    struct {\n        remote_call_args_t args;\n        wchar_t fullpath[MAX_PATH];\n    } data = {0, };\n    DWORD pathlen;\n    intptr_t retval;\n    DWORD last_error;\n    int rv;\n\n    pathlen = GetFullPathNameW(path, MAX_PATH, data.fullpath, NULL);\n    if (pathlen > MAX_PATH) {\n        set_errmsg(\"too long file path: %S\", path);\n        return INJERR_FILE_NOT_FOUND;\n    }\n    if (pathlen == 0) {\n        set_errmsg(\"failed to get the full path: %S\", path);\n        return INJERR_FILE_NOT_FOUND;\n    }\n    data.args.func = injector->load_library;\n    data.args.arg1 = (size_t)injector->data + sizeof(remote_call_args_t);\n\n    rv = remote_call(injector, &data.args, sizeof(data), &retval, &last_error);\n    if (rv != 0) {\n        return rv;\n    }\n    if (retval == 0) {\n        set_errmsg(\"LoadLibrary in the target process failed: %s\", w32strerr(last_error));\n        return INJERR_ERROR_IN_TARGET;\n    }\n    if (handle != NULL) {\n        *handle = (void*)retval;\n    }\n    return 0;\n}\n\nint injector_uninject(injector_t *injector, void *handle)\n{\n    remote_call_args_t args;\n    DWORD pathlen;\n    size_t retval;\n    DWORD last_error;\n    int rv;\n\n    args.func = injector->free_library;\n    args.arg1 = (size_t)handle;\n\n    rv = remote_call(injector, &args, sizeof(args), &retval, &last_error);\n    if (rv != 0) {\n        return rv;\n    }\n    if ((BOOL)retval) {\n        return 0;\n    } else {\n        set_errmsg(\"FreeLibrary in the target process failed: %s\", w32strerr(last_error));\n        return INJERR_ERROR_IN_TARGET;\n    }\n}\n\nint injector_detach(injector_t *injector)\n{\n    if (injector->code != NULL) {\n        VirtualFreeEx(injector->hProcess, injector->code, 0, MEM_RELEASE);\n    }\n    if (injector->hProcess != NULL) {\n        CloseHandle(injector->hProcess);\n    }\n    free(injector);\n    return 0;\n}\n\nconst char *injector_error(void)\n{\n    return errmsg;\n}\n\nint injector_remote_func_addr(injector_t *injector, void *handle, const char* name, size_t *func_addr_out)\n{\n    struct {\n        remote_call_args_t args;\n        char name[512];\n    } data = {0, };\n    intptr_t retval;\n    DWORD last_error;\n    int rv;\n\n    if (strlen(name) >= sizeof(data.name)) {\n        set_errmsg(\"too long function name: %s\", name);\n        return INJERR_FUNCTION_MISSING;\n    }\n\n    data.args.func = injector->get_proc_address;\n    data.args.arg1 = (size_t)handle;\n    data.args.arg2 = (size_t)injector->data + sizeof(remote_call_args_t);\n    strncpy(data.name, name, sizeof(data.name));\n    rv = remote_call(injector, &data.args, sizeof(data), &retval, &last_error);\n    if (rv != 0) {\n        return rv;\n    }\n    if (retval == 0) {\n        set_errmsg(\"GetProcAddress in the target process failed: %s\", w32strerr(last_error));\n        return INJERR_ERROR_IN_TARGET;\n    }\n    *func_addr_out = (size_t)retval;\n    return 0;\n}\n\nint injector_remote_call(injector_t *injector, intptr_t *retval, size_t func_addr, ...)\n{\n    va_list ap;\n    int rv;\n\n    va_start(ap, func_addr);\n    rv = injector_remote_vcall(injector, retval, func_addr, ap);\n    va_end(ap);\n    return rv;\n}\n\nint injector_remote_vcall(injector_t *injector, intptr_t *retval, size_t func_addr, va_list ap)\n{\n    remote_call_args_t args = {0,};\n\n    args.func = func_addr;\n    args.arg1 = va_arg(ap, size_t);\n    args.arg2 = va_arg(ap, size_t);\n    args.arg3 = va_arg(ap, size_t);\n    args.arg4 = va_arg(ap, size_t);\n    args.arg5 = va_arg(ap, size_t);\n    args.arg6 = va_arg(ap, size_t);\n    return remote_call(injector, &args, sizeof(args), retval, NULL);\n}\n\nstatic void set_errmsg(const char *format, ...)\n{\n    va_list ap;\n    int rv;\n\n    va_start(ap, format);\n    rv = vsnprintf(errmsg, sizeof(errmsg), format, ap);\n    va_end(ap);\n    if (rv == -1 || rv >= sizeof(errmsg)) {\n        errmsg[sizeof(errmsg) - 1] = '\\0';\n    }\n}\n\nstatic const char *w32strerr(DWORD err)\n{\n    static char errmsg[512];\n    DWORD len;\n\n    len = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n                         NULL, err, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),\n                         errmsg, sizeof(errmsg), NULL);\n    if (len > 0) {\n        while (len > 0) {\n            char c = errmsg[len - 1];\n            if (c == ' ' || c == '\\n' || c == '\\r') {\n                len--;\n            } else {\n                break;\n            }\n        }\n        errmsg[len] = '\\0';\n    } else if ((int)err >= 0) {\n        sprintf(errmsg, \"win32 error code %d\", err);\n    } else {\n        sprintf(errmsg, \"win32 error code 0x%x\", err);\n    }\n    return errmsg;\n}\n\nstatic USHORT process_arch(HANDLE hProcess)\n{\n    PROCESS_MACHINE_INFORMATION pmi;\n    if (GetProcessInformation(hProcess, ProcessMachineTypeInfo, &pmi, sizeof(pmi))) {\n        // Windows 11\n        return pmi.ProcessMachine;\n    }\n    USHORT process_machine;\n    USHORT native_machine;\n    if (IsWow64Process2(hProcess, &process_machine, &native_machine)) {\n        // Windows 10\n        if (process_machine != IMAGE_FILE_MACHINE_UNKNOWN) {\n            return process_machine;\n        } else {\n            return native_machine;\n        }\n    }\n    /* Windows 8.1 or earlier */\n    /* arch will be either x86 or x64. */\n#if defined(_M_AMD64) || defined(_M_IX86)\n    BOOL is_wow64_proc;\n#if defined(_M_IX86)\n    if (IsWow64Process(GetCurrentProcess(), &is_wow64_proc) && !is_wow64_proc) {\n        // Run on 32-bit Windows\n        return IMAGE_FILE_MACHINE_I386;\n    }\n#endif\n    if (IsWow64Process(hProcess, &is_wow64_proc)) {\n        return is_wow64_proc ? IMAGE_FILE_MACHINE_I386 : IMAGE_FILE_MACHINE_AMD64;\n    }\n#endif\n    return IMAGE_FILE_MACHINE_UNKNOWN;\n}\n\nstatic const char *arch_name(USHORT arch)\n{\n    switch (arch) {\n    case IMAGE_FILE_MACHINE_AMD64:\n        return \"x64\";\n    case IMAGE_FILE_MACHINE_ARM64:\n        return \"arm64\";\n    case IMAGE_FILE_MACHINE_ARMNT:\n        return \"arm\";\n    case IMAGE_FILE_MACHINE_I386:\n        return \"x86\";\n    default:\n        return \"unknown\";\n    }\n}\n"
  },
  {
    "path": "src/windows/injector.def",
    "content": "EXPORTS\n    injector_attach\n    injector_inject\n    injector_detach\n    injector_error\n    injector_inject_w\n    injector_remote_func_addr\n    injector_remote_call\n    injector_remote_vcall\n"
  },
  {
    "path": "tests/Makefile",
    "content": "TEST_PROG_LIBS =\nTEST_TARGET_LDFLAGS =\nTEST_LIBRARY_LDFLAGS = -shared -fPIC\n\nifeq ($(OS),Windows_NT)\n  SRC_DIR = ../src/windows\n  SO_EXT = dll\n  EXE_EXT = .exe\n  INJECTOR_STATIC_LIB = injector-static.lib\n  TEST_PROG_LIBS += -ldbghelp\nelse\n  UNAME_S := $(shell uname -s)\n  ifeq ($(UNAME_S),Darwin)\n    SRC_DIR = ../src/macos\n    SO_EXT = dylib\n  else\n    SRC_DIR = ../src/linux\n    SO_EXT = so\n  endif\n  EXE_EXT =\n  INJECTOR_STATIC_LIB = libinjector.a\n  TEST_TARGET_LDFLAGS += -rdynamic\nendif\n\nBUILD_TARGETS =\n\nifneq ($(wildcard /usr/bin/x86_64-linux-gnu-gcc),)\n  BUILD_TARGETS += x86_64\n  ifneq ($(wildcard /usr/lib/gcc/x86_64-linux-gnu/*/32/libgcc.a),)\n    BUILD_TARGETS += i386\n  endif\n  ifneq ($(wildcard /usr/lib/gcc/x86_64-linux-gnu/*/x32/libgcc.a),)\n    BUILD_TARGETS += x32\n  endif\nendif\n\nifneq ($(wildcard /usr/bin/aarch64-linux-gnu-gcc),)\n  BUILD_TARGETS += arm64\nendif\n\nifneq ($(wildcard /usr/bin/arm-linux-gnueabihf-gcc),)\n  BUILD_TARGETS += armhf\nendif\n\nifneq ($(wildcard /usr/bin/arm-linux-gnueabi-gcc),)\n  BUILD_TARGETS += armel\nendif\n\nifneq ($(wildcard /usr/bin/mips-linux-gnu-gcc),)\n  BUILD_TARGETS += mips\nendif\n\nifneq ($(wildcard /usr/bin/mipsel-linux-gnu-gcc),)\n  BUILD_TARGETS += mipsel\nendif\n\nifneq ($(wildcard /usr/bin/mips64-linux-gnuabi64-gcc),)\n  BUILD_TARGETS += mips64\nendif\n\nifneq ($(wildcard /usr/bin/mips64el-linux-gnuabi64-gcc),)\n  BUILD_TARGETS += mips64el\nendif\n\nifneq ($(wildcard /usr/bin/mipsisa32r6-linux-gnu-gcc),)\n  BUILD_TARGETS += mipsisa32r6\nendif\n\nifneq ($(wildcard /usr/bin/mipsisa32r6el-linux-gnu-gcc),)\n  BUILD_TARGETS += mipsisa32r6el\nendif\n\nifneq ($(wildcard /usr/bin/mipsisa64r6-linux-gnuabi64-gcc),)\n  BUILD_TARGETS += mipsisa64r6\nendif\n\nifneq ($(wildcard /usr/bin/mipsisa64r6el-linux-gnuabi64-gcc),)\n  BUILD_TARGETS += mipsisa64r6el\nendif\n\nifneq ($(wildcard /usr/bin/riscv64-linux-gnu-gcc),)\n  BUILD_TARGETS += riscv64\nendif\n\nifneq ($(wildcard /usr/bin/x86_64-w64-mingw32-gcc),)\n  BUILD_TARGETS += mingw-x64\nendif\n\nifneq ($(wildcard /usr/bin/i686-w64-mingw32-gcc),)\n  BUILD_TARGETS += mingw-32\nendif\n\nCHECK_TARGETS = \\\n  \"x86_64 x86_64\" \\\n  \"x86_64 i386\" \\\n  \"x86_64 x32\" \\\n  \"i386 i386\" \\\n  \"x32 i386\" \\\n  \"arm64 arm64\" \\\n  \"arm64 armhf\" \\\n  \"arm64 armel\" \\\n  \"armhf armhf\" \\\n  \"armhf armel\" \\\n  \"armel armhf\" \\\n  \"armel armel\" \\\n\nall:\n\tSUFFIX= $(MAKE) build\n\ncross: $(BUILD_TARGETS)\n\nx86_64:\n\t@echo \"=============== build: x86_64 ===============\"; \\\n\tCC='cc -m64' SUFFIX=-x86_64 $(MAKE) build\n\ni386:\n\t@echo \"=============== build: i386 ===============\"; \\\n\tCC='cc -m32' SUFFIX=-i386 $(MAKE) build\n\nx32:\n\t@echo \"=============== build: x32 ===============\"; \\\n\tCC='cc -mx32' SUFFIX=-x32 $(MAKE) build\n\narm64:\n\t@echo \"=============== build: arm64 ===============\"; \\\n\tCC=aarch64-linux-gnu-gcc SUFFIX=-arm64 $(MAKE) build\n\narmhf:\n\t@echo \"=============== build: armhf ===============\"; \\\n\tCC=arm-linux-gnueabihf-gcc SUFFIX=-armhf $(MAKE) build\n\narmel:\n\t@echo \"=============== build: armel ===============\"; \\\n\tCC=arm-linux-gnueabi-gcc SUFFIX=-armel $(MAKE) build\n\nmips:\n\t@echo \"=============== build: mips ===============\"; \\\n\tCC='mips-linux-gnu-gcc -mabi=32' SUFFIX=-mips32 $(MAKE) build\n\tCC='mips-linux-gnu-gcc -mabi=n32' SUFFIX=-mipsn32 $(MAKE) build\n\nmipsel:\n\t@echo \"=============== build: mipsel ===============\"; \\\n\tCC='mipsel-linux-gnu-gcc -mabi=32' SUFFIX=-mips32el $(MAKE) build\n\tCC='mipsel-linux-gnu-gcc -mabi=n32' SUFFIX=-mipsn32el $(MAKE) build\n\nmips64:\n\t@echo \"=============== build: mips64 ===============\"; \\\n\tCC=mips64-linux-gnuabi64-gcc SUFFIX=-mips64 $(MAKE) build\n\nmips64el:\n\t@echo \"=============== build: mips64el ===============\"; \\\n\tCC=mips64el-linux-gnuabi64-gcc SUFFIX=-mips64el $(MAKE) build\n\nmipsisa32r6:\n\t@echo \"=============== build: mipsisa32r6 ===============\"; \\\n\tCC='mipsisa32r6-linux-gnu-gcc -mabi=32' SUFFIX=-mipsisa32r6 $(MAKE) build\n\tCC='mipsisa32r6-linux-gnu-gcc -mabi=n32' SUFFIX=-mipsisan32r6 $(MAKE) build\n\nmipsisa32r6el:\n\t@echo \"=============== build: mipsisa32r6el ===============\"; \\\n\tCC='mipsisa32r6el-linux-gnu-gcc -mabi=32' SUFFIX=-mipsisa32r6el $(MAKE) build\n\tCC='mipsisa32r6el-linux-gnu-gcc -mabi=n32' SUFFIX=-mipsisan32r6el $(MAKE) build\n\nmipsisa64r6:\n\t@echo \"=============== build: mipsisa64r6 ===============\"; \\\n\tCC=mipsisa64r6-linux-gnuabi64-gcc SUFFIX=-mipsisa64r6 $(MAKE) build\n\nmipsisa64r6el:\n\t@echo \"=============== build: mipsisa64r6el ===============\"; \\\n\tCC=mipsisa64r6el-linux-gnuabi64-gcc SUFFIX=-mipsisa64r6el $(MAKE) build\n\nriscv64:\n\t@echo \"=============== build: riscv64 ===============\"; \\\n\tCC=riscv64-linux-gnu-gcc SUFFIX=-riscv64 $(MAKE) build\n\nmingw-x64:\n\t@echo \"=============== build: mingw-x64 ===============\"; \\\n\tCC=x86_64-w64-mingw32-gcc SUFFIX=-mingw-x64 OS=Windows_NT $(MAKE) build\n\nmingw-32:\n\t@echo \"=============== build: mingw-32 ===============\"; \\\n\tCC=i686-w64-mingw32-gcc SUFFIX=-mingw-32 OS=Windows_NT $(MAKE) build\n\nbuild: test-prog$(SUFFIX)$(EXE_EXT) test-target$(SUFFIX)$(EXE_EXT) test-library$(SUFFIX).$(SO_EXT)\n\ntest-prog$(SUFFIX)$(EXE_EXT): test-prog.c\n\tcd $(SRC_DIR) && $(MAKE) clean && $(MAKE)\n\t$(CC) $(CFLAGS) -o $@ $^ $(SRC_DIR)/$(INJECTOR_STATIC_LIB) $(TEST_PROG_LIBS)\n\ntest-target$(SUFFIX)$(EXE_EXT): test-target.c\n\t$(CC) $(CFLAGS) $(TEST_TARGET_LDFLAGS) -o $@ $^\n\ntest-library$(SUFFIX).$(SO_EXT): test-library.c\n\t$(CC) $(CFLAGS) $(TEST_LIBRARY_LDFLAGS) -o $@ $^\n\ncheck: all\n\t@if test -x test-prog$(EXE_EXT) -a -x test-target$(EXE_EXT); then \\\n\t   echo \"=============== injector: default, target: default ===============\"; \\\n\t   ./test-prog$(EXE_EXT) || exit $$?; \\\n\t fi;\n\t@for target_pair in $(CHECK_TARGETS); do \\\n\t   set -- $$target_pair; \\\n\t   prog=$$1; target=$$2; \\\n\t   if test -x test-prog-$$prog -a -x test-target-$$target; then \\\n\t     echo \"=============== injector: $$prog, target: $$target ===============\"; \\\n\t     ./test-prog-$$prog $$target || exit $$?; \\\n\t   fi; \\\n\t done\n\nclean:\n\t$(RM) test-prog$(EXE_EXT) test-prog-* test-target$(EXE_EXT) test-target-* test-library.$(SO_EXT) test-library-*.$(SO_EXT)\n\n.PHONY: $(BUILD_TARGETS) build check clean\n"
  },
  {
    "path": "tests/Makefile.win32",
    "content": "all: test-prog.exe test-target.exe test-library.dll\n\nRTFLAG = -MD  # link with dynamic runtime library\n# RTFLAG = -MT  # link with static runtime library\n\nCFLAGS = -nologo $(RTFLAG)\n\n!IF \"$(ARM64EC)\" != \"\"\nCFLAGS = $(CFLAGS) -arm64EC\n!ENDIF\n\ncheck: all\n\t.\\test-prog.exe\n\ntest-prog.exe: test-prog.c ..\\src\\windows\\injector-static.lib\n\t$(CC) $(CFLAGS) /Fetest-prog.exe test-prog.c ..\\src\\windows\\injector-static.lib\n\ntest-target.exe: test-target.c\n\t$(CC) $(CFLAGS) /Fetest-target.exe test-target.c\n\ntest-library.dll: test-library.c\n\t$(CC) /LD $(CFLAGS) /Fetest-library.dll test-library.c\n\nclean:\n\tdel test-target.exe test-target.exp test-target.obj test-target.lib test-prog.exe test-prog.obj test-library.dll test-library.obj\n"
  },
  {
    "path": "tests/test-library.c",
    "content": "#define INCR_ON_INJECTION 13\n#define INCR_ON_UNINJECTION 17\n\n#include <stdint.h>\n\n#ifdef _WIN32\n#include <windows.h>\n\nintptr_t __declspec(dllexport) sum_integers(intptr_t a1, intptr_t a2, intptr_t a3, intptr_t a4, intptr_t a5, intptr_t a6);\n\nBOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved)\n{\n    HMODULE hMod;\n    static int *exit_value_addr;\n\n    switch (reason) {\n    case DLL_PROCESS_ATTACH:\n        hMod = GetModuleHandle(NULL);\n        exit_value_addr = (int *)GetProcAddress(hMod, \"exit_value\");\n        if (exit_value_addr != NULL) {\n            *exit_value_addr += INCR_ON_INJECTION;\n        } else {\n            return FALSE;\n        }\n        break;\n    case DLL_PROCESS_DETACH:\n        *exit_value_addr += INCR_ON_UNINJECTION;\n        break;\n    }\n    return TRUE;\n}\n#elif __APPLE__\n#include <dlfcn.h>\nstatic int *exit_value_addr;\n\n__attribute__((constructor))\nvoid init()\n{\n\texit_value_addr = dlsym(RTLD_DEFAULT, \"exit_value\");\n    *exit_value_addr += INCR_ON_INJECTION;\n}\n\n__attribute__((destructor))\nvoid fini()\n{\n     *exit_value_addr += INCR_ON_UNINJECTION;\n}\n#else //linux\nextern int exit_value;\n\n__attribute__((constructor))\nvoid init()\n{\n    exit_value += INCR_ON_INJECTION;\n}\n\n__attribute__((destructor))\nvoid fini()\n{\n    exit_value += INCR_ON_UNINJECTION;\n}\n#endif\n\nintptr_t sum_integers(intptr_t a1, intptr_t a2, intptr_t a3, intptr_t a4, intptr_t a5, intptr_t a6)\n{\n    return a1 + a2 + a3 + a4 + a5 + a6;\n}\n"
  },
  {
    "path": "tests/test-prog.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * injector - Library for injecting a shared library into a Linux process\n *\n * URL: https://github.com/kubo/injector\n *\n * ------------------------------------------------------\n *\n * Copyright (C) 2018-2023 Kubo Takehiro <kubo@jiubao.org>\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of\n * the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n */\n#include <stdio.h>\n#include <stdlib.h>\n#include <signal.h>\n#include <string.h>\n#include <errno.h>\n#include <sys/types.h>\n#include <inttypes.h>\n#ifdef _WIN32\n#include <windows.h>\n#include <tlhelp32.h>\n#else\n#include <time.h>\n#include <sys/wait.h>\n#include <unistd.h>\n#include <limits.h>\n#endif\n#include \"../include/injector.h\"\n\n#define INCR_ON_INJECTION 13\n#define INCR_ON_UNINJECTION 17\n\n#ifdef _WIN32\n#define EXEEXT \".exe\"\n#define DLLEXT \".dll\"\nstatic BOOL is_under_wine() {\n  static enum {\n    ST_UNKNOWN,\n    ST_WINE,\n    ST_NOT_WINE,\n  } state = ST_UNKNOWN;\n  if (state == ST_UNKNOWN) {\n    if (GetProcAddress(GetModuleHandleA(\"ntdll.dll\"), \"wine_get_version\")) {\n      state = ST_WINE;\n    } else {\n      state = ST_NOT_WINE;\n    }\n  }\n  return state == ST_WINE;\n}\n\nstatic const char *inject_errmsg()\n{\n  if (is_under_wine()) {\n    return \"LoadLibrary in the target process failed: Module not found.\";\n  } else {\n    return \"LoadLibrary in the target process failed: The specified module could not be found.\";\n  }\n}\n#define INJECT_ERRMSG inject_errmsg()\n\nstatic const char *uninject_errmsg()\n{\n  if (is_under_wine()) {\n    return \"FreeLibrary in the target process failed: Invalid handle.\";\n  } else {\n    return \"FreeLibrary in the target process failed: The specified module could not be found.\";\n  }\n}\n#define UNINJECT_ERRMSG uninject_errmsg()\n\n#elif __APPLE__\n#define EXEEXT \"\"\n#define DLLEXT \".dylib\"\n#define INJECT_ERRMSG \"failed to get the full path of 'no such library': No such file or directory\"\n#else\n#define EXEEXT \"\"\n#define DLLEXT \".so\"\n#define INJECT_ERRMSG \"failed to get the full path of 'no such library': No such file or directory\"\n#endif\n\ntypedef struct process process_t;\n\nstatic int process_start(process_t *proc, char *test_target);\nstatic int process_check_module(process_t *proc, const char *module_name, int startswith);\nstatic int process_wait(process_t *proc, int wait_secs);\nstatic void process_terminate(process_t *proc);\n\n#ifdef _WIN32\n\n#define sleep(secs) Sleep(1000 * (secs))\n\nstruct process {\n    DWORD pid;\n    HANDLE hProcess;\n};\n\nstatic int process_start(process_t *proc, char *test_target)\n{\n    STARTUPINFOA si = {sizeof(STARTUPINFOA),};\n    PROCESS_INFORMATION pi;\n\n    if (!CreateProcessA(NULL, test_target, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {\n        printf(\"ERROR: failed to create process: %s\\n\", test_target);\n        return 1;\n    }\n    CloseHandle(pi.hThread);\n    proc->pid = pi.dwProcessId;\n    proc->hProcess = pi.hProcess;\n    return 0;\n}\n\nstatic int process_check_module(process_t *proc, const char *module_name, int startswith)\n{\n    HANDLE hSnapshot;\n    MODULEENTRY32 me;\n    BOOL ok;\n    int len = strlen(module_name);\n\n    do {\n        hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, proc->pid);\n    } while (hSnapshot == INVALID_HANDLE_VALUE && GetLastError() == ERROR_BAD_LENGTH);\n\n    if (hSnapshot == INVALID_HANDLE_VALUE) {\n        printf(\"CreateToolhelp32Snapshot error: %d\\n\", GetLastError());\n        return -1;\n    }\n    me.dwSize = sizeof(me);\n    ok = Module32First(hSnapshot, &me);\n    while (ok) {\n        if ((startswith ? memicmp(me.szModule, module_name, len) : stricmp(me.szModule, module_name)) == 0) {\n            CloseHandle(hSnapshot);\n            return 0;\n        }\n        ok = Module32Next(hSnapshot, &me);\n    }\n    CloseHandle(hSnapshot);\n    return 1;\n}\n\nstatic int process_wait(process_t *proc, int wait_secs)\n{\n    DWORD code;\n    int rv = 1;\n\n    code = WaitForSingleObject(proc->hProcess, wait_secs * 1000);\n    switch (code) {\n    case WAIT_OBJECT_0:\n        GetExitCodeProcess(proc->hProcess, &code);\n        switch (code) {\n        case INCR_ON_INJECTION + INCR_ON_UNINJECTION:\n            printf(\"SUCCESS: The injected library changed the exit_value variable in the target process!\\n\");\n            rv = 0;\n            break;\n        case INCR_ON_INJECTION:\n            printf(\"ERROR: The library was injected but not uninjected.\\n\");\n            break;\n        case 0:\n            printf(\"ERROR: The injected library didn't change the return value of target process!\\n\");\n            break;\n        default:\n            printf(\"ERROR: The target process exited with exit code %d.\\n\", code);\n            break;\n        }\n        break;\n    case WAIT_TIMEOUT:\n        printf(\"ERROR: The target process didn't exit.\\n\");\n        break;\n    defualt:\n        printf(\"ERROR: WaitForSingleObject\\n\");\n        break;\n    }\n    return rv;\n}\n\nstatic void process_terminate(process_t *proc)\n{\n    TerminateProcess(proc->hProcess, 256);\n    CloseHandle(proc->hProcess);\n}\n\n#else\n\nstruct process {\n    pid_t pid;\n    int waited;\n#ifdef __linux__\n    int is_musl;\n#endif\n};\n\nstatic int process_start(process_t *proc, char *test_target)\n{\n    proc->pid = fork();\n    proc->waited = 0;\n    if (proc->pid == 0) {\n        execl(test_target, test_target, NULL);\n        exit(2);\n    }\n    return 0;\n}\n\n#ifdef __APPLE__\n\nstatic int process_check_module(process_t *proc, const char *module_name, int startswith)\n{\n    char buf[PATH_MAX];\n    size_t len = strlen(module_name);\n    FILE *fp;\n\n    sprintf(buf, \"vmmap -w %i\", proc->pid);\n    fp = popen(buf, \"r\");\n    if (fp == NULL) {\n        printf(\"Could not open pipe %s\\n\", buf);\n        return -1;\n    }\n    while (fgets(buf, sizeof(buf), fp) != NULL) {\n        char *p = strrchr(buf, '/');\n\t\tif(p == NULL){\n\t\t\tcontinue;\n\t\t}\n        if (p != NULL && memcmp(p + 1, module_name, len) == 0 && (startswith || p[len + 1] == '\\n')) {\n            pclose(fp);\n            return 0;\n        }\n    }\n    pclose(fp);\n    return 1;\n}\n\nstatic int process_wait(process_t *proc, int wait_secs)\n{\n    int status;\n\tlong start_sec = time(0);\n\tpid_t pid = proc->pid;\n\tdo{\n\t\tif(time(0)-start_sec>wait_secs){\n\t\t\tbreak;\n\t\t}\n\t\tif ((pid = waitpid(pid, &status, WNOHANG)) == -1)\n\t\t{\n\t\t\tprintf(\"wait() error\\n\");\n\t\t} else if(pid != 0){\n\t\t\tif (WIFEXITED(status)) {\n\t\t\t\tint exitcode = WEXITSTATUS(status);\n\t\t\t\tif (exitcode == INCR_ON_INJECTION + INCR_ON_UNINJECTION) {\n\t\t\t\t\tprintf(\"SUCCESS: The injected library changed the exit_value variable in the target process!\\n\");\n\t\t\t\t\treturn 0;\n\t\t\t\t} else if (exitcode == INCR_ON_INJECTION) {\n\t\t\t\t\tprintf(\"ERROR: The library was injected but not uninjected.\\n\");\n\t\t\t\t\treturn 1;\n\t\t\t\t} else if (exitcode == 0) {\n\t\t\t\t\tprintf(\"ERROR: The injected library didn't change the return value of target process!\\n\");\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\tprintf(\"ERROR: The target process exited with exit code %d.\\n\", exitcode);\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t} else if (WIFEXITED(status)) {\n\t\t\t\tint signo = WTERMSIG(status);\n\t\t\t\tprintf(\"ERROR: The target process exited by signal %d.\\n\", signo);\n\t\t\t\treturn 1;\n\t\t\t} else if (WIFSTOPPED(status)) {\n\t\t\t\tint signo = WSTOPSIG(status);\n\t\t\t\tprintf(\"ERROR: The target process stopped by signal %d.\\n\", signo);\n\t\t\t\treturn 1;\n\t\t\t} else {\n\t\t\t\tprintf(\"ERROR: Unexpected waitpid status: 0x%x\\n\", status);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t }\n\t} while (pid == 0);\n    printf(\"ERROR: The target process didn't exit.\\n\");\n    return 1;\n}\n\n#else //linux\nstatic volatile sig_atomic_t caught_sigalarm;\n\nstatic void sighandler(int signo)\n{\n    caught_sigalarm = 1;\n}\nstatic int process_check_module(process_t *proc, const char *module_name, int startswith)\n{\n    char buf[PATH_MAX];\n    size_t len = strlen(module_name);\n    FILE *fp;\n\n    sprintf(buf, \"/proc/%d/maps\", proc->pid);\n    fp = fopen(buf, \"r\");\n    if (fp == NULL) {\n        printf(\"Could not open %s\\n\", buf);\n        return -1;\n    }\n    while (fgets(buf, sizeof(buf), fp) != NULL) {\n        char *p = strrchr(buf, '/');\n        if (p != NULL && memcmp(p + 1, module_name, len) == 0 && (startswith || p[len + 1] == '\\n')) {\n            fclose(fp);\n            return 0;\n        }\n    }\n    fclose(fp);\n    return 1;\n}\n\nstatic int process_wait(process_t *proc, int wait_secs)\n{\n    struct sigaction sigact;\n    int status;\n\n    memset(&sigact, 0, sizeof(sigact));\n    sigact.sa_handler = sighandler;\n    sigaction(SIGALRM, &sigact, NULL);\n    alarm(wait_secs);\n\n    if (waitpid(proc->pid, &status, 0) == proc->pid) {\n        proc->waited = 1;\n        if (WIFEXITED(status)) {\n            int exitcode = WEXITSTATUS(status);\n            if (exitcode == INCR_ON_INJECTION + INCR_ON_UNINJECTION) {\n                if (proc->is_musl) {\n                    printf(\"ERROR: the library was uninjected, which shouldn't be possible on musl.\\n\");\n                    return 0;\n                } else {\n                    printf(\"SUCCESS: The injected library changed the exit_value variable in the target process!\\n\");\n                    return 0;\n                }\n            } else if (exitcode == INCR_ON_INJECTION) {\n                if (proc->is_musl) {\n                    printf(\"SUCCESS: The injected library changed the exit_value variable in the target process!\\n\");\n                    return 0;\n                } else {\n                    printf(\"ERROR: The library was injected but not uninjected.\\n\");\n                    return 1;\n                }\n            } else if (exitcode == 0) {\n                printf(\"ERROR: The injected library didn't change the return value of target process!\\n\");\n                return 1;\n            } else {\n                printf(\"ERROR: The target process exited with exit code %d.\\n\", exitcode);\n                return 1;\n            }\n        } else if (WIFEXITED(status)) {\n            int signo = WTERMSIG(status);\n            printf(\"ERROR: The target process exited by signal %d.\\n\", signo);\n            return 1;\n        } else if (WIFSTOPPED(status)) {\n            int signo = WSTOPSIG(status);\n            printf(\"ERROR: The target process stopped by signal %d.\\n\", signo);\n            return 1;\n        } else {\n            printf(\"ERROR: Unexpected waitpid status: 0x%x\\n\", status);\n            return 1;\n        }\n    }\n    if (caught_sigalarm) {\n        printf(\"ERROR: The target process didn't exit.\\n\");\n    } else {\n        printf(\"ERROR: waitpid failed. (%s)\\n\", strerror(errno));\n    }\n    return 1;\n}\n#endif\nstatic void process_terminate(process_t *proc)\n{\n    int status;\n    if (!proc->waited) {\n        kill(proc->pid, SIGKILL);\n        kill(proc->pid, SIGCONT);\n        waitpid(proc->pid, &status, 0);\n    }\n}\n\n#endif\n\nstatic int test_remote_call(injector_t *injector, void *handle)\n{\n#ifdef INJECTOR_HAS_REMOTE_CALL_FUNCS\n    printf(\"test remote call.\\n\");\n    fflush(stdout);\n\n    size_t func_addr;\n    if (injector_remote_func_addr(injector, handle, \"sum_integers\", &func_addr) != 0) {\n        printf(\"injector_remote_func_addr error:\\n  %s\\n\", injector_error());\n        return -1;\n    }\n    intptr_t retval;\n    intptr_t args[6] = {1, 2, 3, 4, 5, 6};\n    int i;\n    for (i = 0; i < 6; i++) {\n        args[i] += 10;\n        intptr_t expected_retval = args[0] + args[1] + args[2] + args[3] + args[4] + args[5];\n        if (injector_remote_call(injector, &retval, func_addr, args[0], args[1], args[2], args[3], args[4], args[5]) != 0) {\n            printf(\"injector_remote_call error:\\n  %s\\n\", injector_error());\n            return -1;\n        }\n        if (retval != expected_retval) {\n            printf(\"sum_integers(%\" PRIdPTR \", %\" PRIdPTR \", %\" PRIdPTR \", %\" PRIdPTR \", %\" PRIdPTR \", %\" PRIdPTR \") returns %\" PRIdPTR \" (expected %\" PRIdPTR \")\\n\",\n                   args[0], args[1], args[2], args[3], args[4], args[5], retval, expected_retval);\n            return -1;\n        }\n    }\n#endif\n    return 0;\n}\n\nint main(int argc, char **argv)\n{\n    char suffix[20] = {0,};\n    char test_target[64];\n    char test_library[64];\n    injector_t *injector;\n    process_t proc;\n    void *handle = NULL;\n    int rv = 1;\n    int loop_cnt;\n    int can_uninject = 1;\n    int (*inject_func)(injector_t *, const char *, void **) = injector_inject;\n    int i;\n\n    for (i = 1; i < argc; i++) {\n        if (argv[i][0] == '-') {\n            if (strcmp(argv[i], \"--cloned-thread\") == 0) {\n#ifdef INJECTOR_HAS_INJECT_IN_CLONED_THREAD\n                inject_func = injector_inject_in_cloned_thread;\n#else\n                fprintf(stderr, \"injector_inject_in_cloned_thread isn't suported\\n\");\n                return 1;\n#endif\n            } else {\n                fprintf(stderr, \"unknown option %s\\n\", argv[i]);\n                return 1;\n            }\n        } else {\n            snprintf(suffix, sizeof(suffix), \"-%s\", argv[1]);\n            suffix[sizeof(suffix) - 1] = '\\0';\n        }\n    }\n\n    snprintf(test_target, sizeof(test_target), \"test-target%s\" EXEEXT, suffix);\n    snprintf(test_library, sizeof(test_library), \"test-library%s\" DLLEXT, suffix);\n\n    if (process_start(&proc, test_target) != 0) {\n        return 1;\n    }\n    printf(\"target process started.\\n\");\n    fflush(stdout);\n\n    sleep(1);\n\n#ifdef __linux__\n    // Sadly this is not known at compile time, see https://www.openwall.com/lists/musl/2013/03/29/13\n    proc.is_musl = process_check_module(&proc, \"ld-musl-\", 1) == 0;\n    // In musl, dlclose doesn't do anything - see https://wiki.musl-libc.org/functional-differences-from-glibc.html\n    if (proc.is_musl) {\n        can_uninject = 0;\n    }\n#endif\n\n    for (loop_cnt = 0; loop_cnt < 2; loop_cnt++) {\n        const char *errmsg;\n\n        if (injector_attach(&injector, proc.pid) != 0) {\n            printf(\"inject error:\\n  %s\\n\", injector_error());\n            goto cleanup;\n        }\n        printf(\"attached.\\n\");\n        fflush(stdout);\n\n        if (loop_cnt == 0) {\n            if (inject_func(injector, test_library, &handle) != 0) {\n                printf(\"inject error:\\n  %s\\n\", injector_error());\n                goto cleanup;\n            }\n            printf(\"injected. (handle=%p)\\n\", handle);\n            fflush(stdout);\n\n            if (inject_func(injector, \"no such library\", &handle) == 0) {\n                printf(\"injection should fail but succeeded:\\n\");\n                goto cleanup;\n            }\n            errmsg = injector_error();\n            if (strncmp(errmsg, INJECT_ERRMSG, strlen(INJECT_ERRMSG)) != 0) {\n                printf(\"unexpected injection error message: %s\\nexpected: %s\\n\", errmsg, INJECT_ERRMSG);\n                goto cleanup;\n            }\n            if (test_remote_call(injector, handle) != 0) {\n                goto cleanup;\n            }\n#ifdef __linux__\n        } else if (proc.is_musl) {\n            int err = injector_uninject(injector, handle);\n            if (err != INJERR_UNSUPPORTED_TARGET) {\n                printf(\"uninject returns unexpected value: %d\\n\", err);\n                goto cleanup;\n            }\n#endif\n        } else {\n            if (injector_uninject(injector, handle) != 0) {\n                printf(\"uninject error:\\n  %s\\n\", injector_error());\n                goto cleanup;\n            }\n            printf(\"uninjected.\\n\");\n            fflush(stdout);\n\n#ifdef _WIN32\n            if (injector_uninject(injector, NULL) == 0) {\n                printf(\"uninjection should fail but succeeded:\\n\");\n                goto cleanup;\n            }\n            errmsg = injector_error();\n            if (strcmp(errmsg, UNINJECT_ERRMSG) != 0) {\n                printf(\"unexpected uninjection error message: %s\\nexpected: %s\\n\", errmsg, UNINJECT_ERRMSG);\n                goto cleanup;\n            }\n#endif\n        }\n\n        if (injector_detach(injector) != 0) {\n            printf(\"inject error:\\n  %s\\n\", injector_error());\n            goto cleanup;\n        }\n        printf(\"detached.\\n\");\n        fflush(stdout);\n\n        if (can_uninject && process_check_module(&proc, test_library, 0) != loop_cnt) {\n            if (loop_cnt == 0) {\n                printf(\"%s wasn't found after injection\\n\", test_library);\n            } else {\n                printf(\"%s was found after uninjection\\n\", test_library);\n            }\n            goto cleanup;\n        }\n    }\n\n    rv = process_wait(&proc, 8);\ncleanup:\n    process_terminate(&proc);\n    return rv;\n}\n\n"
  },
  {
    "path": "tests/test-target.c",
    "content": "#include <stdio.h>\n\n#ifdef _WIN32\n#include <windows.h>\n#define sleep(secs) Sleep(1000 * (secs))\n#define DLLEXPORT __declspec(dllexport)\n#else\n#include <unistd.h>\n#define DLLEXPORT\n#endif\n\n#define SLEEP_SECS 6\n\nDLLEXPORT int exit_value = 0;\n\nint main()\n{\n    int i;\n\n    /* Use loop instead of sleep(SLEEP_SECS) because\n     * it may be interrupted on Linux.\n     */\n    for (i = 0; i < SLEEP_SECS; i++) {\n        sleep(1);\n\t\tprintf(\"target exit after %i seconds\\n\", SLEEP_SECS - i);\n    }\n\tprintf(\"exit...\\n\");\n    return exit_value;\n}\n"
  },
  {
    "path": "util/ya_getopt.c",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * ya_getopt  - Yet another getopt\n * https://github.com/kubo/ya_getopt\n *\n * Copyright 2015 Kubo Takehiro <kubo@jiubao.org>\n *\n * Redistribution and use in source and binary forms, with or without modification, are\n * permitted provided that the following conditions are met:\n *\n *    1. Redistributions of source code must retain the above copyright notice, this list of\n *       conditions and the following disclaimer.\n *\n *    2. Redistributions in binary form must reproduce the above copyright notice, this list\n *       of conditions and the following disclaimer in the documentation and/or other materials\n *       provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those of the\n * authors and should not be interpreted as representing official policies, either expressed\n * or implied, of the authors.\n *\n */\n#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"ya_getopt.h\"\n\nchar *ya_optarg = NULL;\nint ya_optind = 1;\nint ya_opterr = 1;\nint ya_optopt = '?';\nstatic char *ya_optnext = NULL;\nstatic int posixly_correct = -1;\nstatic int handle_nonopt_argv = 0;\n\nstatic void ya_getopt_error(const char *optstring, const char *format, ...);\nstatic void check_gnu_extension(const char *optstring);\nstatic int ya_getopt_internal(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex, int long_only);\nstatic int ya_getopt_shortopts(int argc, char * const argv[], const char *optstring, int long_only);\nstatic int ya_getopt_longopts(int argc, char * const argv[], char *arg, const char *optstring, const struct option *longopts, int *longindex, int *long_only_flag);\n\nstatic void ya_getopt_error(const char *optstring, const char *format, ...)\n{\n    if (ya_opterr && optstring[0] != ':') {\n        va_list ap;\n        va_start(ap, format);\n        vfprintf(stderr, format, ap);\n        va_end(ap);\n    }\n}\n\nstatic void check_gnu_extension(const char *optstring)\n{\n    if (optstring[0] == '+' || getenv(\"POSIXLY_CORRECT\") != NULL) {\n        posixly_correct = 1;\n    } else {\n        posixly_correct = 0;\n    }\n    if (optstring[0] == '-') {\n        handle_nonopt_argv = 1;\n    } else {\n        handle_nonopt_argv = 0;\n    }\n}\n\nint ya_getopt(int argc, char * const argv[], const char *optstring)\n{\n    return ya_getopt_internal(argc, argv, optstring, NULL, NULL, 0);\n}\n\nint ya_getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex)\n{\n    return ya_getopt_internal(argc, argv, optstring, longopts, longindex, 0);\n}\n\nint ya_getopt_long_only(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex)\n{\n    return ya_getopt_internal(argc, argv, optstring, longopts, longindex, 1);\n}\n\nstatic int ya_getopt_internal(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex, int long_only)\n{\n    static int start, end;\n\n    if (ya_optopt == '?') {\n        ya_optopt = 0;\n    }\n\n    if (posixly_correct == -1) {\n        check_gnu_extension(optstring);\n    }\n\n    if (ya_optind == 0) {\n        check_gnu_extension(optstring);\n        ya_optind = 1;\n        ya_optnext = NULL;\n    }\n\n    switch (optstring[0]) {\n    case '+':\n    case '-':\n        optstring++;\n    }\n\n    if (ya_optnext == NULL && start != 0) {\n        int last_pos = ya_optind - 1;\n\n        ya_optind -= end - start;\n        if (ya_optind <= 0) {\n            ya_optind = 1;\n        }\n        while (start < end--) {\n            int i;\n            char *arg = argv[end];\n\n            for (i = end; i < last_pos; i++) {\n                ((char **)argv)[i] = argv[i + 1];\n            }\n            ((char const **)argv)[i] = arg;\n            last_pos--;\n        }\n        start = 0;\n    }\n\n    if (ya_optind >= argc) {\n        ya_optarg = NULL;\n        return -1;\n    }\n    if (ya_optnext == NULL) {\n        const char *arg = argv[ya_optind];\n        if (*arg != '-') {\n            if (handle_nonopt_argv) {\n                ya_optarg = argv[optind++];\n                start = 0;\n                return 1;\n            } else if (posixly_correct) {\n                ya_optarg = NULL;\n                return -1;\n            } else {\n                int i;\n\n                start = ya_optind;\n                for (i = ya_optind + 1; i < argc; i++) {\n                    if (argv[i][0] == '-') {\n                        end = i;\n                        break;\n                    }\n                }\n                if (i == argc) {\n                    ya_optarg = NULL;\n                    return -1;\n                }\n                ya_optind = i;\n                arg = argv[ya_optind];\n            }\n        }\n        if (strcmp(arg, \"--\") == 0) {\n            ya_optind++;\n            return -1;\n        }\n        if (longopts != NULL && arg[1] == '-') {\n            return ya_getopt_longopts(argc, argv, argv[ya_optind] + 2, optstring, longopts, longindex, NULL);\n        }\n    }\n\n    if (ya_optnext == NULL) {\n        ya_optnext = argv[ya_optind] + 1;\n    }\n    if (long_only) {\n        int long_only_flag = 0;\n        int rv = ya_getopt_longopts(argc, argv, ya_optnext, optstring, longopts, longindex, &long_only_flag);\n        if (!long_only_flag) {\n            ya_optnext = NULL;\n            return rv;\n        }\n    }\n\n    return ya_getopt_shortopts(argc, argv, optstring, long_only);\n}\n\nstatic int ya_getopt_shortopts(int argc, char * const argv[], const char *optstring, int long_only)\n{\n    int opt = *ya_optnext;\n    const char *os = strchr(optstring, opt);\n\n    if (os == NULL) {\n        ya_optarg = NULL;\n        if (long_only) {\n            ya_getopt_error(optstring, \"%s: unrecognized option '-%s'\\n\", argv[0], ya_optnext);\n            ya_optind++;\n            ya_optnext = NULL;\n        } else {\n            ya_optopt = opt;\n            ya_getopt_error(optstring, \"%s: invalid option -- '%c'\\n\", argv[0], opt);\n            if (*(++ya_optnext) == 0) {\n                ya_optind++;\n                ya_optnext = NULL;\n            }\n        }\n        return '?';\n    }\n    if (os[1] == ':') {\n        if (ya_optnext[1] == 0) {\n            ya_optind++;\n            if (os[2] == ':') {\n                /* optional argument */\n                ya_optarg = NULL;\n            } else {\n                if (ya_optind == argc) {\n                    ya_optarg = NULL;\n                    ya_optopt = opt;\n                    ya_getopt_error(optstring, \"%s: option requires an argument -- '%c'\\n\", argv[0], opt);\n                    if (optstring[0] == ':') {\n                        return ':';\n                    } else {\n                        return '?';\n                    }\n                }\n                ya_optarg = argv[ya_optind];\n                ya_optind++;\n            }\n        } else {\n            ya_optarg = ya_optnext + 1;\n            ya_optind++;\n        }\n        ya_optnext = NULL;\n    } else {\n        ya_optarg = NULL;\n        if (ya_optnext[1] == 0) {\n            ya_optnext = NULL;\n            ya_optind++;\n        } else {\n            ya_optnext++;\n        }\n    }\n    return opt;\n}\n\nstatic int ya_getopt_longopts(int argc, char * const argv[], char *arg, const char *optstring, const struct option *longopts, int *longindex, int *long_only_flag)\n{\n    char *val = NULL;\n    const struct option *opt;\n    size_t namelen;\n    int idx;\n\n    for (idx = 0; longopts[idx].name != NULL; idx++) {\n        opt = &longopts[idx];\n        namelen = strlen(opt->name);\n        if (strncmp(arg, opt->name, namelen) == 0) {\n            switch (arg[namelen]) {\n            case '\\0':\n                switch (opt->has_arg) {\n                case ya_required_argument:\n                    ya_optind++;\n                    if (ya_optind == argc) {\n                        ya_optarg = NULL;\n                        ya_optopt = opt->val;\n                        ya_getopt_error(optstring, \"%s: option '--%s' requires an argument\\n\", argv[0], opt->name);\n                        if (optstring[0] == ':') {\n                            return ':';\n                        } else {\n                            return '?';\n                        }\n                    }\n                    val = argv[ya_optind];\n                    break;\n                }\n                goto found;\n            case '=':\n                if (opt->has_arg == ya_no_argument) {\n                    const char *hyphens = (argv[ya_optind][1] == '-') ? \"--\" : \"-\";\n\n                    ya_optind++;\n                    ya_optarg = NULL;\n                    ya_optopt = opt->val;\n                    ya_getopt_error(optstring, \"%s: option '%s%s' doesn't allow an argument\\n\", argv[0], hyphens, opt->name);\n                    return '?';\n                }\n                val = arg + namelen + 1;\n                goto found;\n            }\n        }\n    }\n    if (long_only_flag) {\n        *long_only_flag = 1;\n    } else {\n        ya_getopt_error(optstring, \"%s: unrecognized option '%s'\\n\", argv[0], argv[ya_optind]);\n        ya_optind++;\n    }\n    return '?';\nfound:\n    ya_optarg = val;\n    ya_optind++;\n    if (opt->flag) {\n        *opt->flag = opt->val;\n    }\n    if (longindex) {\n        *longindex = idx;\n    }\n    return opt->flag ? 0 : opt->val;\n}\n"
  },
  {
    "path": "util/ya_getopt.h",
    "content": "/* -*- indent-tabs-mode: nil -*-\n *\n * ya_getopt  - Yet another getopt\n * https://github.com/kubo/ya_getopt\n *\n * Copyright 2015 Kubo Takehiro <kubo@jiubao.org>\n *\n * Redistribution and use in source and binary forms, with or without modification, are\n * permitted provided that the following conditions are met:\n *\n *    1. Redistributions of source code must retain the above copyright notice, this list of\n *       conditions and the following disclaimer.\n *\n *    2. Redistributions in binary form must reproduce the above copyright notice, this list\n *       of conditions and the following disclaimer in the documentation and/or other materials\n *       provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those of the\n * authors and should not be interpreted as representing official policies, either expressed\n * or implied, of the authors.\n *\n */\n#ifndef YA_GETOPT_H\n#define YA_GETOPT_H 1\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n#define ya_no_argument        0\n#define ya_required_argument  1\n#define ya_optional_argument  2\n\nstruct option {\n    const char *name;\n    int has_arg;\n    int *flag;\n    int val;\n};\n\nint ya_getopt(int argc, char * const argv[], const char *optstring);\nint ya_getopt_long(int argc, char * const argv[], const char *optstring,\n                   const struct option *longopts, int *longindex);\nint ya_getopt_long_only(int argc, char * const argv[], const char *optstring,\n                        const struct option *longopts, int *longindex);\n\nextern char *ya_optarg;\nextern int ya_optind, ya_opterr, ya_optopt;\n\n#ifndef YA_GETOPT_NO_COMPAT_MACRO\n#define getopt ya_getopt\n#define getopt_long ya_getopt_long\n#define getopt_long_only ya_getopt_long_only\n#define optarg ya_optarg\n#define optind ya_optind\n#define opterr ya_opterr\n#define optopt ya_optopt\n#define no_argument ya_no_argument\n#define required_argument ya_required_argument\n#define optional_argument ya_optional_argument\n#endif\n\n#if defined(__cplusplus)\n}\n#endif\n\n#endif\n"
  }
]