[
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: cargo\n    directories:\n      - /\n      - tools/memcached_benchmark\n    schedule:\n      interval: weekly\n    cooldown: # applies only to non-security updates\n      semver-patch-days: 3 # wait 3 days before applying patch updates\n      semver-minor-days: 7\n      semver-major-days: 14\n  - package-ecosystem: github-actions\n    directory: /\n    schedule:\n      interval: weekly\n  # - package-ecosystem: gitsubmodule\n  #   directory: /\n  #   schedule:\n  #     interval: weekly\n"
  },
  {
    "path": ".github/workflows/dco-check.yml",
    "content": "name: DCO Check\n\non:\n  pull_request:\n\njobs:\n  check:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: KineticCafe/actions-dco@6e1652ef3027ce128e65e6edd215ae053350bd16 # v2.1.1\n"
  },
  {
    "path": ".github/workflows/memcached_benchmark.yml",
    "content": "name: memcached_benchmark\n\non:\n  push:\n  pull_request:\n\nenv:\n  CARGO_TERM_COLOR: always\n\njobs:\n  changes:\n    if: github.repository == 'rex-rs/rex'\n    runs-on: ubuntu-latest\n    permissions:\n      pull-requests: read\n    outputs:\n      bench: ${{ steps.filter.outputs.bench }}\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1\n        id: filter\n        with:\n          filters: |\n            bench:\n              - 'tools/memcached_benchmark/**'\n\n  build:\n    needs: changes\n    if: ${{ needs.changes.outputs.bench == 'true' }}\n    runs-on: ubuntu-latest\n    defaults:\n      run:\n        working-directory: ./tools/memcached_benchmark\n\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - id: filter\n        uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1\n        with:\n          filters: |\n            bench:\n              - 'tools/memcached_benchmark/**'\n      - uses: cachix/install-nix-action@616559265b40713947b9c190a8ff4b507b5df49b # v31.10.4\n\n      - name: Build\n        run: nix develop --command bash -e -c 'cargo fmt --check --verbose && cargo build -r --verbose'\n\n      - name: Run tests\n        run: nix develop --command bash -e -c 'cargo test --verbose && cargo test -r --verbose'\n"
  },
  {
    "path": ".github/workflows/meson.yml",
    "content": "name: Meson Build and Test\n\non:\n  push:\n    branches: [main, ci]\n  pull_request:\n    branches: [main]\n\nenv:\n  CARGO_TERM_COLOR: always\n\njobs:\n  changes:\n    if: github.repository == 'rex-rs/rex'\n    runs-on: ubuntu-latest\n    permissions:\n      pull-requests: read\n    outputs:\n      meson: ${{ steps.filter.outputs.meson }}\n      nix: ${{ steps.filter.outputs.nix }}\n    steps:\n      # For pull requests it's not necessary to checkout the code\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1\n        id: filter\n        with:\n          predicate-quantifier: 'every'\n          filters: |\n            nix: &nix\n              - '**'\n              - '!docs/**'\n              - '!tools/**'\n              - '!**/*.md'\n              - '!.github/workflows/!(meson).yml'\n            meson:\n              - *nix\n              - '!flake.nix'\n              - '!flake.lock'\n\n  build_and_test:\n    needs: changes\n    if: ${{ needs.changes.outputs.meson == 'true' }}\n    runs-on: [self-hosted, gentoo]\n    concurrency:\n      group: build_and_test-${{ github.ref_name }}\n      cancel-in-progress: true\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          submodules: recursive\n\n      - name: Cache Rex build directory\n        uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5\n        with:\n          path: build\n          key: ${{ runner.os }}-${{ runner.name }}-meson-${{ hashFiles('rex-native.ini', 'meson.build') }}\n\n      - name: Setup Rex build directory\n        run: meson setup --native-file rex-native.ini --reconfigure ./build\n\n      - name: Compile Rex deps\n        run: meson compile -C build build_deps\n\n      - name: Compile Rex samples\n        run: meson compile -C build\n\n      - name: Run Rex sanity tests\n        run: meson test -C build\n\n  # build_with_nix:\n  #   needs: changes\n  #   if: ${{ needs.changes.outputs.nix == 'true' }}\n  #   runs-on: [self-hosted, nix]\n  #   concurrency:\n  #     group: build_with_nix_fhs-${{ github.ref_name }}\n  #     cancel-in-progress: true\n  #   steps:\n  #     - name: Checkout repository\n  #       uses: actions/checkout@v4\n  #       with:\n  #         submodules: recursive\n  #\n  #     - name: Setup Rex build directory\n  #       run: meson setup --native-file rex-native.ini --reconfigure ./build\n  #       shell: nix develop -v -L .#rex --command bash -e {0}\n  #\n  #     - name: Compile Rex deps\n  #       run: meson compile -C build build_deps\n  #       shell: nix develop -v -L .#rex --command bash -e {0}\n  #\n  #     - name: Compile Rex samples\n  #       run: meson compile -C build\n  #       shell: nix develop -v -L .#rex --command bash -e {0}\n\n  build_with_nix_fhs:\n    needs: changes\n    if: ${{ needs.changes.outputs.nix == 'true' }}\n    runs-on: [self-hosted, nix]\n    concurrency:\n      group: build_with_nix_fhs-${{ github.ref_name }}\n      cancel-in-progress: true\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          submodules: recursive\n\n      - name: Setup Rex build directory\n        run: nix run .#fhsExec -- -c \"meson setup --native-file rex-native.ini --reconfigure ./build\"\n\n      - name: Compile Rex deps\n        run: nix run .#fhsExec -- -c \"meson compile -C build build_deps\"\n\n      - name: Compile Rex samples\n        run: nix run .#fhsExec -- -c \"meson compile -C build\"\n"
  },
  {
    "path": ".github/workflows/rustfmt.yml",
    "content": "name: Formatting check\n\non:\n  push:\n  pull_request:\n\njobs:\n  formatting:\n    if: github.repository == 'rex-rs/rex'\n    name: cargo fmt\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          submodules: true\n      - name: Determine nightly date from rust submodule\n        id: rust-version\n        run: |\n          # compiler_date in src/stage0 is the previous stable's release date,\n          # which is the same day the beta branch is cut and nightly bumps forward.\n          # The day before is the last nightly that matches this version's rustfmt.\n          COMPILER_DATE=$(grep '^compiler_date=' rust/src/stage0 | cut -d= -f2)\n          NIGHTLY_DATE=$(date -d \"${COMPILER_DATE} - 1 day\" +%Y-%m-%d)\n          echo \"nightly_date=${NIGHTLY_DATE}\" >> \"$GITHUB_OUTPUT\"\n          echo \"Using nightly-${NIGHTLY_DATE}\"\n      - name: Install matching rust nightly\n        env:\n          NIGHTLY_DATE: ${{ steps.rust-version.outputs.nightly_date }}\n        run: |\n          rustup toolchain install \"nightly-${NIGHTLY_DATE}\" --component rustfmt\n          rustup default \"nightly-${NIGHTLY_DATE}\"\n      - name: formatting rex code\n        run: cargo fmt --verbose --check\n      - name: formatting samples code\n        run: |\n          for d in $(find ./samples -name Cargo.toml); do\n            echo \"→ Processing $d\"\n            cargo fmt --manifest-path $d --verbose --check\n          done\n"
  },
  {
    "path": ".github/workflows/update-nix.yml",
    "content": "name: Update Nix Dependencies\non:\n  workflow_dispatch:\n  # push:\n  #   branches: [ ci ] # for testing\n  schedule:\n    - cron: '0 0 * * 1' # Monday morning at 00:00 UTC\n\npermissions:\n  contents: write\n  pull-requests: write\n\njobs:\n  update-nix:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6\n        with:\n          token: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: Install Nix\n        uses: DeterminateSystems/nix-installer-action@main\n\n      - name: Update root flake.lock\n        uses: DeterminateSystems/update-flake-lock@main\n        with:\n          commit-msg: \"nix: update root flake.lock\"\n          pr-title: \"nix-flake: update nix dependencies\"\n          pr-labels: |\n            dependencies\n            nix\n          pr-body: |\n            Automated update of nix flake dependencies.\n\n            Updated lock files:\n            - `flake.lock`\n            - `tools/memcached_benchmark/flake.lock`\n\n      - name: Update memcached_benchmark flake.lock\n        uses: DeterminateSystems/update-flake-lock@main\n        with:\n          flake-lock-path: tools/memcached_benchmark/flake.lock\n          commit-msg: \"nix: update memcached_benchmark flake.lock\"\n          pr-title: \"nix-flake: update nix dependencies\"\n          pr-labels: |\n            dependencies\n            nix\n          pr-body: |\n            Automated update of nix flake dependencies.\n\n            Updated lock files:\n            - `flake.lock`\n            - `tools/memcached_benchmark/flake.lock`\n"
  },
  {
    "path": ".gitignore",
    "content": ".vscode*\n.cargo\n!samples/*/.cargo\n!tools/*/.cargo\nsamples/*/event-trigger\nsamples/*/loader\nsamples/*/entry\nsamples/*/.cache\ntest_dict.yml.zst\nbench_entries.yml.zst\ncompile_commands.json\n!rex/.cargo\n\n# Generated by Cargo\n# will have compiled files and executables\ntarget/\n.direnv\n.envrc\n.cache\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"linux\"]\n\tpath = linux\n\turl = git@github.com:rex-rs/linux.git\n\tbranch = rex-linux\n[submodule \"rust\"]\n\tpath = rust\n\turl = git@github.com:rex-rs/rust.git\n\tbranch = rex-rust\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[workspace]\nmembers = [\n\t# rex lib\n\t\"rex\",\n\n\t# macros\n\t\"rex-macros\",\n]\n\nresolver = \"2\"\nexclude = [\"samples\", \"rust\", \"tools\", \"scripts\"]\n\n[workspace.package]\nauthors = [\"Rex Contributors\"]\nrepository = \"https://github.com/rex-rs/rex\"\nedition = \"2021\"\n\n[workspace.dependencies]\nproc-macro-error = { version = \"1.0\", default-features = false }\nproc-macro2 = { version = \"1\", default-features = false }\npaste = { version = \"1\" }\nsyn = { version = \"2\", features = [\"full\"] }\nquote = { version = \"1\" }\nrex-macros = { path = \"./rex-macros\" }\n\n[profile.dev]\ndebug = 0\npanic = \"abort\"\n\n[profile.release]\ndebug = 0\npanic = \"abort\"\nlto = true\n"
  },
  {
    "path": "LICENSE",
    "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\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (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\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  <signature of Ty Coon>, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "README.md",
    "content": "```\n ____  _______  __  _____      _                 _\n|  _ \\| ____\\ \\/ / | ____|_  _| |_ ___ _ __  ___(_) ___  _ __  ___\n| |_) |  _|  \\  /  |  _| \\ \\/ / __/ _ \\ '_ \\/ __| |/ _ \\| '_ \\/ __|\n|  _ <| |___ /  \\  | |___ >  <| ||  __/ | | \\__ \\ | (_) | | | \\__ \\\n|_| \\_\\_____/_/\\_\\ |_____/_/\\_\\\\__\\___|_| |_|___/_|\\___/|_| |_|___/\n\n```\n\n# Rex Kernel Extensions\n\n[![CI](https://img.shields.io/github/actions/workflow/status/rex-rs/rex/.github%2Fworkflows%2Fmeson.yml?label=ci)](https://github.com/rex-rs/rex/actions)\n[![Gentoo](./docs/image/gentoo-badge3.svg)](https://www.gentoo.org)\n\n#### Table of Contents\n\n- [What is Rex](#what-is-rex)\n- [Example program](#example-program)\n- [Build and run](#build-and-run)\n- [Documentations](#documentations)\n- [Why Rex](#why-rex)\n- [License](#license)\n\n## What is Rex\n\nRex is a safe and usable kernel extension framework that allows loading and\nexecuting Rust kernel extension programs in the place of eBPF. Unlike\neBPF-based frameworks such as [Aya](https://aya-rs.dev), Rex programs do\nnot go through the in-kernel verifier, instead, the programs are\nimplemented in the safe subset of Rust, on which the Rust compiler performs\nthe needed safety checks and generates native code directly. This approach\navoids the overly restricted verification requirements (e.g., program\ncomplexity constraints) and the resulting arcane verification errors, while\nat the same time potentially provides a better optimization opportunity in\nthe native compiler backend (i.e., LLVM) than the eBPF backend + in-kernel\nJIT approach.\n\nRex currently supports the following features:\n\n- 5 eBPF program types: `kprobe`, `perf_event`, `tracepoint`, `xdp`, and\n  `tc`.\n- invocation of eBPF helper functions that are commonly used by these\n  programs\n- interaction with eBPF maps\n- RAII-style management of kernel resources obtainable by programs\n- cleanup and in-kernel exception handling of Rust runtime panics with call\n  stack traces\n- kernel stack (only when CFG cannot be computed statically) and\n  termination safety from a thin in-kernel runtime\n- bindings and abstractions of kernel data types commonly needed by eBPF\n  programs\n\n## Example program\n\nThe following example implements a kprobe program that attaches to a\nselected system call and injects an error (specified by `errno`) to the\nsystem call on a process (specified by its `pid`). The full example,\nincluding the loader program, can be found under\n[samples/error_injector](samples/error_injector).\n\n```Rust\n#![no_std]\n#![no_main]\n\nuse rex::kprobe::kprobe;\nuse rex::map::RexHashMap;\nuse rex::pt_regs::PtRegs;\nuse rex::rex_kprobe;\nuse rex::rex_map;\nuse rex::Result;\n\n#[allow(non_upper_case_globals)]\n#[rex_map]\nstatic pid_to_errno: RexHashMap<i32, u64> = RexHashMap::new(1, 0);\n\n#[rex_kprobe]\npub fn err_injector(obj: &kprobe, ctx: &mut PtRegs) -> Result {\n    obj.bpf_get_current_task()\n        .map(|t| t.get_pid())\n        .and_then(|p| obj.bpf_map_lookup_elem(&pid_to_errno, &p).cloned())\n        .map(|e| obj.bpf_override_return(ctx, e))\n        .ok_or(0)\n}\n```\n\nMore sample programs can be found under [samples](samples).\n\n## Build and run\n\nYou can find the detailed guide [here](docs/getting-started.md).\n\n## Documentations\n\nAdditional design documentations can be found under [docs](docs).\n\n## Why Rex\n\nThe existing eBPF extension relies on the in-kernel eBPF verifier to\nprovide safety guarantees. This unfortunately leads to usability issues\nwhere safe programs are rejected by the verifier, including but not limited\nto:\n\n- programs may exceed the inherent complexity contraints of static\n  verification\n- compilers may not generate verifier-friendly code\n- same logic may need to be implemented in a certain way to please the\n  verifier\n\nRex aims to address these issues by directly leveraging the safety\nguarantee from _safe Rust_. Developers can implement their programs in any\nway that can be written in safe Rust with [few\nrestrictions](docs/rust_rex_subset.md), and no longer need to worry about\nprogram complexity, the code generator, or finding the (many time\ncounter-intuitive) way of expressing the same logic to please the verifier.\n\nWe demonstrate this with the implementation of the [BPF Memcached Cache\n(BMC)](https://github.com/Orange-OpenSource/bmc-cache), a state-of-the-art\nextension program for Memcached acceleration. As a complex eBPF program,\nBMC is forced to be splitted into several components connected by BPF\ntail-calls and use awkward loop/branch implementations to please the\nverifier, which are totally not needed in [its Rex\nimplementation](samples/bmc).\n\nFor example, we show the code in cache invalidation logic of the BPF-BMC\nthat searches for a `SET` command in the packet payload:\n\n```C\n// Searches for SET command in payload\nfor (unsigned int off = 0;\n     off < BMC_MAX_PACKET_LENGTH &&  payload + off + 1 <= data_end;\n     off++) {\n    if (set_found == 0 && payload[off] == 's' &&\n        payload + off + 3 <= data_end && payload[off + 1] == 'e' &&\n        payload[off + 2] == 't') {\n            off += 3;\n            set_found = 1;\n    }\n    ...\n}\n```\n\nThe code not only introduces an extra constraint in the loop (`off <\nBMC_MAX_PACKET_LENGTH`) solely for passing the verifier, but also employs\nrepeated boilerplate code to check packet ends (`data_end`) and cumbersome\nlogic to match the `\"set\"` string in the packet.\n\nNone of these burdens is needed with the power of safe Rust in Rex, which\nhas no complexity limits and provides more freedom on the implementation:\n\n```rust\nlet set_iter = payload.windows(4).enumerate().filter_map(|(i, v)| {\n    if v == b\"set \" {\n      Some(i)\n    } else {\n      None\n    }\n});\n\n```\n\nThe full implementation of BMC in Rex can be found at\n[samples/bmc](samples/bmc).\n\n## License\n\nRex is licensed under the GPLv2 license. The submodules (Linux, Rust, LLVM)\nin this repo are licensed under their own terms. Please see the\ncorresponding license files for more details. Additionally, the memcached\nbenchmark is licensed under the MIT license.\n\n## Talks\n- Open Source Summit North America 2025: https://youtu.be/4r7ECxEaGqM\n- USENIX ATC 2025: https://youtu.be/phJ-fb5lEA8\n- Linux Plumbers Conference 2025: https://youtu.be/ivcLS4LFfKE\n"
  },
  {
    "path": "docs/entry-insertion.md",
    "content": "# Entry point code Insertion\n\n## Motivation\n\nTo allow Rust extension code to be called from the kernel, an FFI\nentry-point function is needed to wrap around the user-defined extension\nfunction. This wrapper function needs to handle certain unsafe operations,\nfor example, context conversion for XDP and perf event programs. Because of\nthis, it should never be implemented by the user. For example, interpreting\nan XDP context as perf event context and perform the context conversion\nspecific to perf-event clearly violates memory and type safety and could\nresult in undefined behavior.\n\nTherefore, we choose to automatically generate the entry point code during\ncompilation for the Rust extension programs. Since Rust by default uses\nLLVM as its code generation backend. We performs the generation of entry\ncode in the middle-end on LLVM IR.\n\n## Implementation\n\nThe entry point insertion is implemented as an LLVM pass\n(`RexEntryInsertion`) that operates on the compilation unit that contains\nthe Rust extension programs. This LLVM pass can be enabled via the\n`enable_rex` codegen option in rustc, which sets the corresponding pass for\nthe LLVM backend.\n\nTake the [error_injector sample](../samples//error_injector/src/main.rs) as\nan example:\n\n```Rust\n#![no_std]\n#![no_main]\n\nuse rex::kprobe::kprobe;\nuse rex::map::RexHashMap;\nuse rex::pt_regs::PtRegs;\nuse rex::rex_kprobe;\nuse rex::rex_map;\nuse rex::Result;\n\n#[allow(non_upper_case_globals)]\n#[rex_map]\nstatic pid_to_errno: RexHashMap<i32, u64> = RexHashMap::new(1, 0);\n\n#[rex_kprobe]\npub fn err_injector(obj: &kprobe, ctx: &mut PtRegs) -> Result {\n    obj.bpf_get_current_task()\n        .map(|t| t.get_pid())\n        .and_then(|p| obj.bpf_map_lookup_elem(&pid_to_errno, &p).cloned())\n        .map(|e| obj.bpf_override_return(ctx, e))\n        .ok_or(0)\n}\n```\n\nHere, the\n[`rex_kprobe`](https://github.com/rex-rs/rex/blob/93777ca3ad238ad3ace1d45614933f277ab587e8/rex-macros/src/lib.rs#L47)\nproc-macro defines a kprobe program object  in section (`rex/kprobe/*`)\nusing the\n[`const`](https://doc.rust-lang.org/std/keyword.const.html#compile-time-evaluable-functions)\nfunction `kprobe::new`, which takes the program function `rex_kprobe` is\nspecified on and its literal name as arguments:\n\n```Rust\n#![no_std]\n#![no_main]\n\nuse rex::kprobe::kprobe;\nuse rex::map::RexHashMap;\nuse rex::pt_regs::PtRegs;\nuse rex::rex_kprobe;\nuse rex::rex_map;\nuse rex::Result;\n\n#[allow(non_upper_case_globals)]\n#[rex_map]\nstatic pid_to_errno: RexHashMap<i32, u64> = RexHashMap::new(1, 0);\n\npub fn err_injector(obj: &kprobe, ctx: &mut PtRegs) -> Result {\n    obj.bpf_get_current_task()\n        .map(|t| t.get_pid())\n        .and_then(|p| obj.bpf_map_lookup_elem(&pid_to_errno, &p).cloned())\n        .map(|e| obj.bpf_override_return(ctx, e))\n        .ok_or(0)\n}\n\n#[used]\n#[link_section = \"rex/kprobe\"]\nstatic PROG_err_injector: kprobe = kprobe::new(err_injector, \"err_injector\");\n```\n\nUnder the hood, the `kprobe` object is defined as the following:\n\n```Rust\n#[repr(C)]\npub struct kprobe {\n    rtti: u64,\n    prog: fn(&Self, &mut PtRegs) -> Result,\n    name: &'static str,\n}\n```\n\nThe `rtti` field stores the corresponding\n[`bpf_prog_type`](https://elixir.bootlin.com/linux/v5.15.128/source/include/uapi/linux/bpf.h#L919)\nenum value (i.e. `BPF_PROG_TYPE_KPROBE` in this case). `prog` is a function\npointer that points to the user-defined extension program function. `name`\nholds the user-intended name of the program, in a string literal form (as\nmentioned above, the proc-macros in `rex-macros` always set this to the\nliteral name of the program function).\n\nAt LLVM-IR level, the `RexEntryInsertion` will iterate over all global\nvariables and look for variables with the special `rex/*` sections\ngenerated by proc-macros from `rex-macros`. For the found program objects,\nit will then generate the entry point based on the object contents.\nBecause the `kprobe::new` function is a `const` function. The object is\ninitialized with a constant expression that can be parsed by the\n`RexEntryInsertion` pass. This effectively allows the pass to obtain the\nprogram type (via `rtti`), the actual extension function (via `prog`), and\nthe intended name (via `name`).\n\nThe pass will construct a new `fn (*const()) -> u32` function with the\nspecified name and eBPF link section, which will be used as the entry point\nfunction the kernel can invoke. This function takes in the context pointer\n(as `*mut ()`) and invokes the special program-type-specific entry function\nin the `rex` crate. The code of the aforementioned example would be\nmodified as (the process happens at LLVM-IR stage, but here Rust is used\nfor clarity):\n\n```Rust\n#![no_std]\n#![no_main]\n\nuse rex::kprobe::kprobe;\nuse rex::map::RexHashMap;\nuse rex::pt_regs::PtRegs;\nuse rex::rex_kprobe;\nuse rex::rex_map;\nuse rex::Result;\n\n#[allow(non_upper_case_globals)]\n#[rex_map]\nstatic pid_to_errno: RexHashMap<i32, u64> = RexHashMap::new(1, 0);\n\n#[inline(always)]\npub fn err_injector(obj: &kprobe, ctx: &mut PtRegs) -> Result {\n    obj.bpf_get_current_task()\n        .map(|t| t.get_pid())\n        .and_then(|p| obj.bpf_map_lookup_elem(&pid_to_errno, &p).cloned())\n        .map(|e| obj.bpf_override_return(ctx, e))\n        .ok_or(0)\n}\n\n#[used]\n#[link_section = \"rex/kprobe\"]\nstatic PROG_err_injector: kprobe = kprobe::new(err_injector, \"err_injector\"););\n\n#[link_section = \"kprobe\"]\n#[no_mangle]\npub fn err_injector(ctx: *mut ()) -> u32 {\n    rex::__rex_entry_kprobe(&PROG_err_injector, ctx)\n}\n```\n\n`__rex_entry_kprobe` is the tracepoint specific entry function defined in\nthe `rex` crate (not to be confused with the generated kernel entry point).\nThe function essentially calls `kprobe::prog_run` that converts the context\nto the type specific to the program and invokes the `prog` function. In\nthis way the program context conversion and other preparation for execution\nis safely abstracted away from the users.\n\n### Add new program type support\n\nThe only file needs to be updated is\n[llvm/include/llvm/Transforms/Rex/RexProgType.def](https://github.com/rex-rs/llvm-project/blob/rex-llvm-rebase/llvm/include/llvm/Transforms/Rex/RexProgType.def).\nThe basic syntex is:\n\n```C\nREX_PROG_TYPE_1(<BPF_PROG_TYPE_ENUM>, <program_type in RT crate>, <sec name>)\n```\n\nIf the program type has more than 1 section names, use `REX_PROG_TYPE_2`\ninstead, which will support 2 names.  Therefore, for `tracepoint` this is:\n\n```C\nREX_PROG_TYPE_2(BPF_PROG_TYPE_TRACEPOINT, tracepoint, \"tracepoint\", \"tp\")\n```\n\nRelevant files:\n- LLVM pass:\n  - [llvm/lib/Transforms/Rex/RexInsertEntry.cpp](https://github.com/rex-rs/llvm-project/blob/rex-llvm-rebase/llvm/lib/Transforms/Rex/RexInsertEntry.cpp)\n  - [llvm/include/llvm/Transforms/Rex/RexInsertEntry.h](https://github.com/rex-rs/llvm-project/blob/rex-llvm-rebase/llvm/include/llvm/Transforms/Rex/RexInsertEntry.h)\n  - [llvm/include/llvm/Transforms/Rex/RexProgType.def](https://github.com/rex-rs/llvm-project/blob/rex-llvm-rebase/llvm/include/llvm/Transforms/Rex/RexProgType.def)\n- Program-type-specific entry function (defined using the\n  `define_prog_entry` macro):\n  - [rex/src/lib.rs](https://github.com/rex-rs/rex/blob/main/rex/src/lib.rs)\n- Kprobe implementation (can be generalized to other programs):\n  - [rex/src/kprobe/kprobe_impl.rs](https://github.com/rex-rs/rex/blob/main/rex/src/kprobe/kprobe_impl.rs)\n"
  },
  {
    "path": "docs/exception-handling.md",
    "content": "# Exception handling and runtime mechanism\n\nThis document will cover the following:\n\n- [Handling of Rust panics (language exceptions)](#handling-of-rust-panics-in-kernel-space)\n  - [Kernel dispatch and landingpad](#kernel-stack-unwinding)\n  - [Rust panic handler and cleanup mechanism](#resource-cleanup-in-rust)\n\n## Handling of Rust panics in kernel space\n\nIn userspace, Rust panics are essentially the same as C++ exceptions and\nare handled based on [Itanium\nABI](https://llvm.org/docs/ExceptionHandling.html#itanium-abi-zero-cost-exception-handling).\nThat is, when a panic is triggered, the control flow will be redirect to\nthe unwind library (e.g. `libgcc` or `llvm-libunwind`). The unwind library\nwill then unwind the program stack. For each function call frame, it will\ninvoke the `personality` routine to look for feasible landingpads which\ncontains cleaup and (possibly) exception handling code. The unwind process\nends when either the exception is handled (e.g. by a C++ `catch`) or no\nhandler is found.\n\nP.S. The actual Itanium ABI is more complicated than described here, e.g.\nthe unwind library runs two passes on the stack, once for searching\nlandingpads, and another time for executing landingpads code.\n\nHowever, the Itanium EH ABI is not suitable in our case for the following\nreasons:\n\n- It adds too much complexity, as the userspace unwind libraries are not\n  directly usable.\n- It usually requires dynamic allocation for certain exception contexts,\n  which may not be available to kernel extensions (e.g. kprobe executes in\n  interrupt contexts and is therefore not sleepable).\n- It allows failures during the unwinding which cannot be tolerated in\n  kernel space. Incomplete cleanup means leaking kernel resources.\n- It generally executes destructors for all existing objects on the stack,\n  but executing untrusted, user-defined destructors (via the `Drop` trait\n  in Rust) may not be safe.\n\nTherefore, in our framework we implement our exception handling mechanism.\nIt can be divided into two parts: stack unwinding in the kernel and\nresource cleanup in the runtime crate.\n\n### Kernel stack unwinding\n\nWe need to be able support graceful exception handling in kernel space,\ni.e.  the extension program should be terminated without bringing down the\nkernel.  The idea is to transfer the exceptional control flow back to the\nreturn address of the extension program and reset the stack and frame\npointer to ensure the context remains valid. In this way, the program would\nact as if it just returned normally.\n\nThe implementation consists the `rex_dispatcher_func` to dispatch Rex\nprograms so that rust panics can be handled. The dispatcher have a\nprototype of:\n\n```C\nextern asmlinkage unsigned int rex_dispatcher_func(\n        const void *ctx,\n        const struct bpf_prog *prog,\n        unsigned int (*bpf_func)(const void *,\n                                 const struct bpf_insn *));\n```\n\nwhich shares a similar signature as `bpf_dispatcher_nop_func` but with the\n`struct bpf_insn` array argument replaced by a pointer to the program\nstruct, as Rex does not work with eBPF bytecode.\n\nThe function first saves the current stack pointer to the top of the\nper-CPU Rex-specific stack, and then switches the stack before calling into\nthe program.\n\nIf the execution is successful (i.e. no exceptions), the function will just\nreturn normally and the old stack pointer will be restored with a `pop`.\n\n```\n   +-----------------------+\n   | rex_dispatcher_func:  |\n   | ...                   |\n   | movq %gs:rex_sp, %rbp |\n   | movq %rsp, (%rbp)     |\n   | movq %rbp, %rsp       |                +-----------+\n   | call *%rdx            |--------------->| rex_prog: |\n   |                       |                | ...       |\n   | rex_exit:             |<---------------| ret       |\n   | popq %rsp             |                +-----------+\n   | ...                   |\n   | ret                   |\n   +-----------------------+\n```\n\nUnder exceptional cases (where a rust panic is fired), `rust_begin_unwind`\n(i.e. panic handler) will transfer the control flow to the `rex_landingpad`\nC function in the kernel, which, after dumping some information to the\nkernel ring buffer, will call `rex_landingpad_asm`. `rex_landingpad_asm`\nsets a default reutrn value, restores the stack pointer to the top of the\nRex stack, i.e. the same address when program returns without an exception,\nand issues an direct jump to the `rex_exit` label in the middle of\n`rex_dispatcher_func`.\n\n```\n         +-----------------------+\n         | rex_dispatcher_func:  |\n         | ...                   |\n         | movq %gs:rex_sp, %rbp |\n         | movq %rsp, (%rbp)     |\n         | movq %rbp, %rsp       |                +-----------+\n         | call *%rdx            |--------------->| rex_prog: |\n         |                       |         +------| ...       |\n   +---->| rex_exit:             |         |      | ret       |\n   |     | popq %rsp             |         |      +-----------+\n   |     | ...                   |         |\n   |     | ret                   |         | panic!()\n   |     |                       |         |\n   |     | rex_landingpad_asm:   |<-----+  |      +-------------------------+\n   |     | ...                   |      |  +----->| rex_landingpad:         |\n   |     | movq %gs:rex_sp, %rsp |      |         | ...                     |\n   +-----| jmp rex_exit          |      +---------| call rex_landingpad_asm |\n         +-----------------------+                +-------------------------+\n```\n\nThe Rex stack uses the same layout as other kernel stacks -- the pointer to\nthe previous stack is stored in the top-most entry of the Rex stack. This,\ncombined with `bpf-ksyms`, allows smooth integration with the ORC unwinder\nand provides meaningful stack traces:\n\n```console\n[   12.568364][  T208] rex: Panic from Rex prog: called `Option::unwrap()` on a `None` value\n[   12.568622][  T208] CPU: 3 UID: 0 PID: 208 Comm: userapp Not tainted 6.13.0-rex+ #226\n[   12.568854][  T208] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.16.3-20240910_120124-localhost 04/01/2014\n[   12.569236][  T208] Call Trace:\n[   12.569345][  T208]  <REX>\n[   12.569428][  T208]  dump_stack_lvl+0x6e/0xa8\n[   12.569559][  T208]  rex_landingpad+0x64/0xb0\n[   12.569704][  T208]  rex_prog_4168211f00000000::rust_begin_unwind+0x15a/0x1a0\n[   12.569944][  T208]  rex_prog_4168211f00000000::core::panicking::panic_fmt+0x9/0x10\n[   12.570188][  T208]  rex_prog_4168211f00000000::core::panicking::panic+0x53/0x60\n[   12.570423][  T208]  rex_prog_4168211f00000000::core::option::unwrap_failed+0x9/0x10\n[   12.570668][  T208]  rex_prog_4168211f00000000::err_injector+0x8f/0xa0\n[   12.570879][  T208]  rex_dispatcher_func+0x32/0x32\n[   12.571045][  T208]  </REX>\n[   12.571137][  T208]  <TASK>\n[   12.571229][  T208]  trace_call_bpf+0x1a1/0x1f0\n[   12.571363][  T208]  ? __x64_sys_dup+0x1/0xd0\n[   12.571468][  T208]  kprobe_perf_func+0x4e/0x260\n[   12.571582][  T208]  ? kmem_cache_free+0x29/0x290\n[   12.571718][  T208]  ? __cfi___x64_sys_dup+0x10/0x10\n[   12.571879][  T208]  kprobe_ftrace_handler+0x115/0x1a0\n[   12.572046][  T208]  ? __x64_sys_dup+0x5/0xd0\n[   12.572189][  T208]  0xffffffffa02010c8\n[   12.572310][  T208]  ? __x64_sys_dup+0x1/0xd0\n[   12.572452][  T208]  __x64_sys_dup+0x5/0xd0\n[   12.572582][  T208]  do_syscall_64+0x42/0xb0\n[   12.572722][  T208]  entry_SYSCALL_64_after_hwframe+0x4b/0x53\n[   12.572910][  T208] RIP: 0033:0x7f6039f0ee9d\n[   12.573050][  T208] Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 90 f3 0f 1e fa 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 8b 0d 33 bf 0b 00 f7 d8 64 89 01 48\n[   12.573579][  T208] RSP: 002b:00007ffd562cee08 EFLAGS: 00000246 ORIG_RAX: 0000000000000020\n[   12.573779][  T208] RAX: ffffffffffffffda RBX: 00007ffd562cef28 RCX: 00007f6039f0ee9d\n[   12.573967][  T208] RDX: 000055cc27f9b988 RSI: 00007ffd562cef38 RDI: 0000000000000000\n[   12.574150][  T208] RBP: 0000000000000001 R08: 00007f6039ffada0 R09: 000055cc27f9a730\n[   12.574348][  T208] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000\n[   12.574600][  T208] R13: 00007ffd562cef38 R14: 00007f603a02a000 R15: 000055cc27f9b988\n[   12.574810][  T208]  </TASK>\n```\n\nFor further information please refer to the [actual\ncode](https://github.com/rex-rs/linux/blob/rex-linux/arch/x86/net/rex_64.S).\n\n### Resource cleanup in Rust\n\nNot using the existing ABI-based exception handling / stack unwinding\nscheme means we need to handle resource cleanup in our own way. We make the\nobservation that the only resources that requires cleanup are the resources\nobtained from kernel helper functions. This is because of the restricted\nprograming interface exposed to these extension programs, which disallow\ndirect kernel resource alloation (e.g. allocate memory, directly access a\nlock, etc).\n\nThis brings us chance to create a light-weight resource clean up scheme. We\ncan record allocated kernel resources and their destructors on-the-fly\nduring program execution. When termination is needed, the destructors of\nallocated resources are invoked to release the resources. Since only the\ntrusted kernel crate that interfaces with the kernel resources is\nresponsible for implementing the aforementioned destructors, all the\ncleanup code is trusted and guaranteed not to fail.\n\nThe PoC implemention uses `CleanupEntry` to represent an allocated\nresource:\n\n```Rust\npub(crate) type CleanupFn = fn(*const ()) -> ();\n\n#[derive(Debug, Copy, Clone)]\n#[repr(C)]\npub(crate) struct CleanupEntry {\n    pub(crate) valid: u64,\n    pub(crate) cleanup_fn: Option<CleanupFn>,\n    pub(crate) cleanup_arg: *const (),\n}\n```\n\nAn instance of the struct is supposed to be instantiated in the constructor\nof the kernel resource binding types in the runtime crate:\n\n- `valid` should be set to 1\n- `cleanup_fn` should point to a function provided in `impl` of the binding\n  type, which takes in a pointer to the object and runs `drop` on it. The\n  `drop` handler is also responsible for setting `valid` to 0.\n- `cleanup_arg` should point to the newly created object. It is used as the\n  argument to `cleanup_fn`.\n\nNote:\n\n1. `valid` field is of type `u64`. This may not seem space effcient at a\n   glance, but since both `cleanup_fn` and `cleanup_arg` are 64 bit large.\n   The alignment of the struct is 64 bits anyway.\n2. According to\n   [Rustonomicon](https://doc.rust-lang.org/nomicon/repr-rust.html) and\n   [Rust doc](https://doc.rust-lang.org/std/option/#representation),\n   `Option<CleanupFn>` has the same size and bit-level representation as\n   `CleanupFn` as long as it is a `Some`. This is important because on the\n   kernel side it can be treated as a `void (*)(void *)`.\n\nThe created struct is then stored in a per-CPU array `rex_cleanup_entries`\nin the kernel. This also implies that a C binding for `CleanupEntry` is\nneeded in the kernel:\n\n```C\nstruct rex_cleanup_entry {\n    u64 valid;\n    void *cleanup_fn;\n    void *cleanup_arg;\n};\n```\n\nNote:\n\n1. Using `void *` to store function pointer is not standard compliant,\n   though at ABI level it is always a 64-bit value and should work\n   correctly.  We should change it to a real function pointer: `void\n   (*)(void *)`.\n2. Currently, the array is statically allocated with a capacity of 64. This\n   **may not** be sustainable.\n\nDuring normal execution, the `drop` handlers are executed normally so the\nkernel resource will be released and the `CleanupEntry` will be\ninvalidated.\n\nUpon a panic, the control flow will transfer to `rust_begin_unwind` (i.e.\nthe Rust panic handler). `rust_begin_unwind` will traverse the array on\ncurrent CPU and free any resources allocated by invoking\n`(cleanup_fn)(cleanup_arg)`.  It then invalidate these entries.\n\nCode references:\n\n1. [Rust side `CleanupEntry` and panic handler\n   implementation](https://github.com/rex-rs/rex/blob/main/rex/src/panic.rs)\n2. [Kernel side binding type and per-CPU\n   array](https://github.com/rex-rs/linux/blob/cd07f685c08b6087da0b1468a97d75c3de51e296/kernel/bpf/core.c#L3146)\n"
  },
  {
    "path": "docs/getting-started.md",
    "content": "# Getting started (p20250206)\n\nBuilding Rex extensions requires modifications to the toolchain (Rust and\nLLVM) and running Rex extensions requires modifications to the Linux\nkernel.  The steps below describe how to set up both the toolchain and\nkernel for running Rex extensions in a VM.\n\nRex currently only supports the `x86-64` (`amd64`) architecture. Running\nRex in VMs addtionally requires\n[`KVM`](https://linux-kvm.org/page/Main_Page) to be available on the host\nmachine.\n\n## Nix flake\n\nUsing Nix, a package manager, allows you to bypass these dependency\nrequirements below.\n\nCheck out the https://nixos.org/download/ for installation instructions,\nthe single-user installation should be sufficient.\n\n## Dependencies:\n\nThe following tools/libraries are required. Older versions are not\nguaranteed to (or guaranteed not to) work. This list does not include\nstandard kernel build dependencies.\n- `clang+LLVM (>= 18.1.0)`\n- `cmake`\n- `elfutils`\n- `libstdc++ (>=13)` for missing `c++23` support in LLVM's `libcxx`\n- `meson`\n- `mold`\n- `ninja`\n- `python (>= 3.11)`\n- `QEMU`\n- `rust-bindgen`\n\n## Repo setup and build\n\nClone this repo and its submodules:\n\n```bash\ngit clone https://github.com/rex-rs/rex.git rex-kernel\ncd rex-kernel\ngit submodule update --init --progress\n```\n\nIf you are using Nix, the following additional step is required.\n\n```bash\nnix develop --extra-experimental-features nix-command --extra-experimental-features flakes\n```\n\nIt will launch a Nix shell with all necessary dependencies installed.\nAll subsequent steps should be carried out within this shell.\n\nRex uses `meson` as its build system, to get started, first set up `meson`\nin Rex:\n\n```bash\nmeson setup --native-file rex-native.ini ./build/\n```\n\nRex requries the modified kernel and its `libbpf` library, which resides in\nthe `linux` directory after submodule initialization. Rex also uses custom\nLLVM passes in the Rust compiler to generate additional code and\ninstruments the extension programs, therefore,\n[bootstraping](https://en.wikipedia.org/wiki/Bootstrapping_(compilers)) the\nRust compiler is required. The Rust toolchain source can be found under the\n`rust` directory as another submodule.\n\nBuilding these dependencies is a one-time effort with the following\ncommand:\n\n```bash\nmeson compile -C build build_deps\n```\n\nThis will build the kernel and its `libbpf`. It will also bootstrap the\nRust compiler and build the relevant tools (e.g., `cargo`, `clippy`, etc).\n\nWith the linux and Rust setup, all Rex sample programs can then be built\nwith:\n\n```bash\nmeson compile -C build\n```\n\n## Run `hello` example\nFirst boot the VM:\n\n```bash\ncd build/linux\n../../scripts/q-script/yifei-q # use ../scripts/q-script/nix-q instead if you are using Nix\n```\n\nInside the VM:\n\n```bash\ncd ../samples/hello\n./loader &\n./event-trigger\n```\n\nThe following output should be printed out:\n\n```console\n<...>-245     [002] d...1    18.417331: bpf_trace_printk: Rust triggered from PID 245.\n```\n\n## Troubleshooting\n\n### Building dependencies:\n\nThis step includes compiling the Linux kernel which can get quite resource\nintensive. In our tests `6GB` is the minimum value for which compiling\nLinux is possible, this means you might not be able to use Rex on machines\nwith 6GB or less RAM. A sign that you ran into Out-Of-Memory (OOM) error is\nif you encounter this warning:\n\n```bash\n/root/rex/linux/scripts/link-vmlinux.sh: line 113: 55407 Killed                  LLVM_OBJCOPY=\"${OBJCOPY}\" ${PAHOLE} -J ${PAHOLE_FLAGS} ${1}\n```\n\nAnd error:\n\n```bash\nFAILED: load BTF from vmlinux: invalid argument\n```\n\nOr similar problems.\n\nFor WSL users, it is recommended to allocate more RAM to WSL before\nstarting this step since WSL by default only utilizes half the RAM\navailable on the host machine:\n\nFrom a Powershell instance, create and open a `.wslconfig` file in your\nhome directory:\n\n```bash\nnotepad $HOME/.wslconfig\n```\n\nAdd the following lines to the file then save:\n\n```bash\n[wsl2]\nmemory=8GB\nswap=8GB\n```\n\nYou should change the value to how much memory you want to allocate to WSL.\n\nAnother issue that may happen is bootstrap failure due to the missing\n`libLLVM-19-rex.so`:\n\n```console\n  --- stderr\n  llvm-config: error: libLLVM-19-rex.so is missing\n  thread 'main' panicked at compiler/rustc_llvm/build.rs:264:16:\n  command did not execute successfully: \"/home/chin39/Documents/rex-kernel/build/rust-build/x86_64-unknown-linux-gnu/llvm/bin/llvm-config\" \"--link-shared\" \"--libs\" \"--system-libs\" \"asmparser\" \"bitreader\" \"bitwriter\" \"coverage\" \"instrumentation\" \"ipo\" \"linker\" \"lto\" \"x86\"\n  expected success, got: exit status: 1\n  stack backtrace:\n     0: rust_begin_unwind\n               at /rustc/9fc6b43126469e3858e2fe86cafb4f0fd5068869/library/std/src/panicking.rs:665:5\n     1: core::panicking::panic_fmt\n               at /rustc/9fc6b43126469e3858e2fe86cafb4f0fd5068869/library/core/src/panicking.rs:76:14\n     2: build_script_build::output\n     3: build_script_build::main\n     4: core::ops::function::FnOnce::call_once\n  note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.\nBuild completed unsuccessfully in 0:00:12\nFAILED: cargo rustc\nenv 'RUSTFLAGS=-Z threads=8 -C target-cpu=native -C codegen-units=1 -C link-arg=-fuse-ld=mold -C link-arg=-Wl,-O1 -C link-arg=-Wl,--as-needed -C link-arg=-flto=thin' /usr/bin/python3 ../rust/x.py install --config=../rust/rex-config.toml --build-dir=./rust-build --set install.prefix=./rust-dist\nninja: build stopped: subcommand failed.\n```\n\nNotably this may happen as a result of [`ba85ec815c2f (\"rust: enable more\noptimizations and features in bootstrap\nconfig\")`](https://github.com/rex-rs/rex/commit/ba85ec815c2fc9721e3b466d1c296bd7dd79b1b3),\nas it changes the linkage of `libLLVM` from static to dynamic, but rust\nbootstrap process does not rebuild `libLLVM.so` following the change.\nThe issue can be fixed by removing the build directory created by meson and\nstarting a clean build.\n\n### Building the Rex samples:\n\nThere are some caveats before you run this step. By default the `ninja`\nbuild tool uses a quite high level of parallelism, which might again cause\nOOM on personal machines. A sign of this happenning is if you try this step\nand run into similar errors to:\n\n```bash\nerror: could not compile `core` (lib)\n\nCaused by:\n    process didn't exit successfully:\n```\n\nTo resolve this problem, try running with fewer commands in parallel using\nthe `-j` argument, for example to run with 4 commands in parallel:\n\n```bash\nmeson compile -C build -j 4\n```\n\nOur tests indicate a peak memory usage of 12GB with `-j 8`, so if you have\nless RAM it's helpful to keep the `-j` argument below 8.\n\n### Booting the QEMU VM:\n\nBy default our QEMU VM runs on 8GB of memory. To reduce this, open the qemu\nscripts using an editor and locate line 300:\n\n```bash\nMEMORY=8192\n```\n\nAnd change this value to the number you want. Rex has been tested to work\nwith 4GB or `MEMORY=4096`.\n"
  },
  {
    "path": "docs/kernel-symbols.md",
    "content": "# Handling of kernel symbols\n\nThis document covers dynamic kernel symbol resolution.\n\nThe `rex` crate serves as an interface for the extension programs to\ninteract with the kernel. To accomplish this, the crate will need to access\nkernel symbols. For example, invoking kernel helper functions requires\nknowing the kernel address of the target helper function symbol.  These\nkernel symbols includes not only BPF helper functions, but also certain\nper-cpu variables and other kernel functions (these comes partly from our\nprevious effort on rewriting kernel helpers, but it is also used by the\nstack unwind/protection and panic cleanup mechanism).\n\nBefore [`36b91e1aab92: (\"libiu: support dynamic symbol\nrelocation\")`](https://github.com/rex-rs/rex/commit/36b91e1aab92a28cf341852c1ffd187597736d60),\nthe `rex` crate directly compiles the address of the kernel symbols in. The\nbuild script uses `nm` to resolve addresses of the needed kernel symbols\n(specified in a special section of `Cargo.toml`) and generates the\n`stub.rs` file. The rest of the crate can use the generated `xxx_addr`\nfunction to get the address of kernel symbol `xxx` as an `u64`. The code\ncan then transmute the value into the appropriate type (e.g. a function\npointer for helper functions). This way of kernel symbol resolution causes\nseveral problems:\n\n1. The compiled executable will contain kernel addresses, which should not\n   be leaked to userspace.\n2. It requires KASLR to be turned off (because addresses from\n   `nm`/`System.map` are static), which is not portable on KASLR-enabled\n   kernels.\n3. When ever kernel image layout changes (e.g. changes in function offset),\n   the extension program needs to be re-compiled.\n4. The transmuted stub becomes a function pointer for helper functions,\n   which, after inlining, hinders further optimization on stack\n   instrumentation (the instrumentation can only be omitted if there are no\n   indirect calls / recursions).\n\nTherefore, it is reasonable to defer the kernel symbol resolution to load\ntime.  At this point, the kernel always knows where the symbols are located\n(even with KASLR), which solves problems 2 and 3. At the same time, the\nfinal executable will not contain any actual kernel address, addressing\nproblem 1. In order to avoid the need of an indirect call (problem 4), we\nchoose to implement the kernel symbol resolution the same way dynamic\nlinking works in userspace -- declare the needed kernel symbols as external\nsymbols and let the compiler generate relocation entries for these symbols.\n\nThe new implementation involves the following:\n\n1. Declare the needed kernel symbols as `extern \"C\"` and with appropriate\n   type.  For example `bpf_probe_read_kernel` is declared as:\n\n   ```Rust\n   extern \"C\" {\n       /// `long bpf_probe_read_kernel(void *dst, u32 size, const void *unsafe_ptr)`\n       pub(crate) fn bpf_probe_read_kernel(\n           dst: *mut (),\n           size: u32,\n           unsafe_ptr: *const (),\n       ) -> i64;\n   }\n   ```\n\n   `extern \"C\"` specifies that the symbol uses the C ABI, which matches\n   that of the actual in-kernel object/function (check the\n   [Rustonomicon](https://doc.rust-lang.org/nomicon/other-reprs.html) for\n   more information). The declarations can be found in\n   [`src/stub.rs`](https://github.com/rex-rs/rex/blob/main/rex/src/stub.rs).\n\n2. To make it easy to generate the relocations, we add a dummy library,\n   [`librexstub`](https://github.com/rex-rs/rex/tree/main/rex/librexstub),\n   that provides \"fake\" definitions of the symbols. The extension programs\n   will link against this library dynamically so that a dynamic relocation\n   entry is generated for each kernel symbol and the linker will not\n   complain about undefined symbols. For example, dumping relocations for\n   the\n   [`error_injector`](https://github.com/rex-rs/rex/tree/main/samples/error_injector)\n   sample gives the following:\n\n   ```console\n   $ objdump -R target/x86_64-unknown-none/release/error_injector\n\n   target/x86_64-unknown-none/release/error_injector:     file format elf64-x86-64\n\n   DYNAMIC RELOCATION RECORDS\n   OFFSET           TYPE              VALUE\n   0000000000003e58 R_X86_64_RELATIVE  *ABS*+0x0000000000002029\n   0000000000003e68 R_X86_64_RELATIVE  *ABS*+0x0000000000002000\n   0000000000003fc0 R_X86_64_RELATIVE  *ABS*+0x0000000000001210\n   0000000000003ff8 R_X86_64_RELATIVE  *ABS*+0x0000000000001020\n   0000000000003fb8 R_X86_64_GLOB_DAT  this_cpu_off\n   0000000000003fc8 R_X86_64_GLOB_DAT  pcpu_hot\n   0000000000003fd0 R_X86_64_GLOB_DAT  rex_cleanup_entries\n   0000000000003fd8 R_X86_64_GLOB_DAT  rex_landingpad\n   0000000000003fe0 R_X86_64_GLOB_DAT  just_return_func\n   0000000000003fe8 R_X86_64_GLOB_DAT  rex_termination_state\n   0000000000003ff0 R_X86_64_GLOB_DAT  bpf_map_lookup_elem\n   ```\n\n   The relocations with type `R_X86_64_GLOB_DAT` are the kernel symbol\n   relocations generated from dynamic linking, where the `OFFSET` denotes the\n   address offset within the binary and the `VALUE` specifies the actual symbol\n   name.\n\n   Other relocations with type `R_X86_64_RELATIVE` are a result from\n   position-independent executables (PIE).  In PIE, function invocations\n   involve a IP-relative call that indexes into the global offset table\n   (GOT) that stores the absolute address of the function. The GOT entries\n   are generated as relocations that are patched at the program load time.\n   For example, `3fc0 R_X86_64_RELATIVE  *ABS*+0x1270` specifies that the\n   value at offset `3fc0` of the binary needs to be patched to the absolute\n   start address of the binary (after it is mapped into memory) plus\n   `0x1270`.\n\n   The library exists solely for the generation of relocations, it is never\n   mapped into the kernel with the program and the symbols defined in the\n   library are therefore never accessed. At the same time, because the\n   symbols are not accessed, their types are not relevant, only the name\n   matters. The build script of the `rex` crate automatically builds the\n   library and adds the needed linker flags so that users can just use\n   `cargo` to build the programs.\n\n3. At load time, librex parses the relocation entries to find out the\n   offsets and symbol names (accessible by symbol table index), and send\n   them to the kernel. The decision to let the loader library parse the\n   relocation entries is to reduce the complexity of code in the kernel and\n   take advantage of the existing userspace ELF libraries (we use\n   `elfutils`, the same library used by `libbpf`).  Each dynamic symbol\n   relocation is the stored in an\n   [`rex_dyn_sym`](https://github.com/rex-rs/linux/blob/cd07f685c08b6087da0b1468a97d75c3de51e296/include/uapi/linux/bpf.h#L1472-L1475)\n\n   struct:\n\n   ```C\n   struct rex_dyn_sym {\n       __u64\toffset; // symbol offset\n       __u64\tsymbol; // symbol name string (actually a char *)\n   };\n   ```\n\n   When invoking the `bpf(2)` syscall to load the program, the library will\n   pass an array of `struct rex_dyn_sym` to the kernel (by setting pointer\n   to the start address and the size in the\n   [`bpf_attr`](https://github.com/rex-rs/linux/blob/cd07f685c08b6087da0b1468a97d75c3de51e296/include/uapi/linux/bpf.h#L1591-L1592)\n   union).\n\n   The kernel copies the array into kernel space and queries each symbol\n   name against `kallsyms` to lookup the in-kernel address of the symbol,\n   it then patches the value at the specified offset to that address.\n\nThe same symbol resolution mechanism is applied to maps as well.\n"
  },
  {
    "path": "docs/librex.md",
    "content": "# LIBREX\n\n`librex` serves as the loader library for Rex programs -- similar to what\n`libbpf` is to eBPF programs -- but in a simpler way.\n\n### APIs\n\n`librex` only contains the code that loads Rex programs from ELF binaries,\nother operations (e.g., attachment, map manipulation, etc) are delegated to\nthe existing code in `libbpf`.\n\nTherefore, the library only exposes the following simple APIs:\n```c\nstruct rex_obj *rex_obj_load(const char *file_path);\nstruct bpf_object *rex_obj_get_bpf(struct rex_obj *obj);\nvoid rex_set_debug(int val);\n```\n\nThe `rex_obj_load` function loads the Rex programs from the ELF binary\nidentified by the `file_path` argument into the kernel. It returns a\npointer to the corresponding `rex_obj` that encapsulates information about\nthe loaded programs and created maps. If there is an error, a null pointer\nis returned.\n\nThe `rex_obj_get_bpf` returns a pointer to the equivalent `bpf_object` of\nthe `obj` argument, which can be subsequently passed to `libbpf` APIs. If\nthere is an error, a null pointer is returned.\n\n**Note**: The returned pointer from both functions above are **non-owning**\npointers, which means the caller of these function should not try to\n`free`/`realloc`/`delete` the pointer. The ownership of the pointers is\nmanaged by `librex` internally and will be automatically freed after the\nprogram terminates.\n\nThe `rex_set_debug` function can be used to toggle the internal logging\nmechanism of `librex` (with `(bool)val` determining whether logging is\nenabled). This will most likely be helpful during debugging.\n"
  },
  {
    "path": "docs/rust_rex_subset.md",
    "content": "### Rex subset of Rust\n\n- `std`\n  - depends on libc, therefore not available in standalone mode\n- `alloc`\n  - Rex currently does not hook onto kernel's allocator\n- unsafe\n  - can break any safety guarrantee\n- `core::mem::forget` and `core::mem::ManuallyDrop`\n  - take ownership and “forget” about the value **without running its\n    destructor**.\n  - lifetime related: disrupts resource cleanup\n- `core::intrinsics::abort`:\n  - uses an illegal instruction and therefore can crash the kernel.\n- `core::simd`\n  - no simd/fp allowed in the kernel in the first place\n"
  },
  {
    "path": "flake.nix",
    "content": "{\n  description = \"A flake for the REX project\";\n\n  inputs = {\n    nixpkgs.url = \"github:nixos/nixpkgs/nixos-unstable\";\n  };\n\n  outputs = { self, nixpkgs, ... }:\n    let\n      system = \"x86_64-linux\";\n\n      basePkgs = import nixpkgs {\n        inherit system;\n      };\n\n      remoteNixpkgsPatches = [\n        {\n          meta.description = \"cc-wrapper: remove -nostdlibinc\";\n          url = \"https://github.com/chinrw/nixpkgs/commit/2a5bd9cecd9ae28d899eb9bf434255a9fa09cbb0.patch\";\n          sha256 = \"sha256-TBmNtH8C5Vp1UArLtXDk+dxEzUR3tohjPMpJc9pIEN8=\";\n        }\n      ];\n\n      patchedNixpkgsSrc = basePkgs.applyPatches {\n        name = \"nixpkgs-patched\";\n        src = basePkgs.path;\n        patches = map basePkgs.fetchpatch remoteNixpkgsPatches;\n      };\n\n      # patchedBindgen =\n      #   (self: super: {\n      #     rust-bindgen-unwrapped = super.rust-bindgen-unwrapped.overrideAttrs (finalAttrs: oldAttrs: {\n      #       src = super.fetchFromGitHub {\n      #         owner = \"rust-lang\";\n      #         repo = \"rust-bindgen\";\n      #         rev = \"20aa65a0b9edfd5f8ab3e038197da5cb2c52ff18\";\n      #         sha256 = \"sha256-OrwPpXXfbkeS7SAmZDZDUXZV4BfSF3e/58LJjedY1vA=\";\n      #       };\n      #       cargoDeps = pkgs.rustPlatform.fetchCargoVendor {\n      #         inherit (finalAttrs) pname src version;\n      #         hash = finalAttrs.cargoHash;\n      #       };\n      #       cargoHash = \"sha256-e94pwjeGOv/We6uryQedj7L41dhCUc2wzi/lmKYnEMA=\";\n      #     });\n      #   });\n\n      patchedPkgs = import patchedNixpkgsSrc {\n        inherit system;\n        # overlays = [ patchedBindgen ];\n      };\n\n      pkgs = import nixpkgs {\n        inherit system;\n        # overlays = [ overrideLLVM ];\n      };\n\n      wrapCC = cc: pkgs.wrapCCWith {\n        inherit cc;\n        extraBuildCommands = ''\n          # Remove the line that contains \"-nostdlibinc\"\n          sed -i 's|-nostdlibinc||g' \"$out/nix-support/cc-cflags\"\n          echo \" -resource-dir=${pkgs.llvmPackages.clang}/resource-root\" >> \"$out/nix-support/cc-cflags\"\n          echo > \"$out/nix-support/add-local-cc-cflags-before.sh\"\n        '';\n      };\n\n\n\n      # wrappedClang = wrapCC pkgs.llvmPackages.clang.cc;\n      # lib = nixpkgs.lib;\n\n      # Use unwrapped clang & lld to avoid warnings about multi-target usage\n      rexPackages = with pkgs; [\n        # Kernel builds\n        autoconf\n        bc\n        binutils\n        bison\n        cmake\n        diffutils\n        elfutils\n        elfutils.dev\n        fakeroot\n        findutils\n        flex\n        git\n        gcc\n        getopt\n        gnumake\n        ncurses\n        openssl\n        openssl.dev\n        pkg-config\n        xz\n        xz.dev\n        zlib\n        zlib.dev\n        bpftools\n\n        cargo-pgo\n\n        ninja\n        patchedPkgs.rust-bindgen\n        pahole\n        strace\n        zstd\n        perf-tools\n        # linuxKernel.packages.linux_latest.perf\n\n        # Clang kernel builds\n        patchedPkgs.llvmPackages.clang\n        patchedPkgs.llvmPackages.llvm\n        # wrappedClang\n        # llvmPackages.libcxxStdenv\n        lld\n        mold\n\n        qemu\n        file\n        util-linux\n        hostname\n        sysctl\n\n        perf-tools\n\n        # for llvm/Demangle/Demangle.h\n        libllvm.lib\n        libllvm.dev\n        libgcc\n        libclang.lib\n        libclang.dev\n\n        # meson deps\n        meson\n        curl\n        perl\n\n        bear # generate compile commands\n        rsync # for make headers_install\n        gdb\n\n        # bmc deps\n        iproute2\n        memcached\n        python3\n\n        # Rex utils\n        zoxide # in case host is using zoxide\n        openssh # q-script ssh support\n        bat\n        fd\n        eza\n        zsh\n      ];\n\n      llvmBuildFHSEnv = pkgs.buildFHSEnv.override { stdenv = pkgs.llvmPackages.stdenv; };\n      fhsBase =\n        {\n          name = \"rex-env\";\n          targetPkgs = pkgs: rexPackages ++ [ pkgs.systemd pkgs.file ];\n\n          profile = ''\n            export NIX_ENFORCE_NO_NATIVE=0\n            export PATH=$(realpath \"./build/rust-dist/bin\"):$PATH\n            export RUST_BACKTRACE=1\n          '';\n        };\n\n      fhsRex = llvmBuildFHSEnv (fhsBase // {\n        runScript = \"zsh\";\n      });\n\n      # FHS environment for running arbitrary commands\n      fhsExec = llvmBuildFHSEnv (fhsBase // {\n        name = \"rex-exec\";\n        runScript = pkgs.writeScript \"fhs-exec-wrapper\" ''\n          #!${pkgs.bash}/bin/bash\n          exec bash \"$@\"\n        '';\n      });\n\n    in\n    {\n      devShells.\"${system}\" = {\n        default = fhsRex.env;\n\n        rex = pkgs.mkShell {\n          packages = rexPackages;\n          # Disable default hardening flags. These are very confusing when doing\n          # development and they break builds of packages/systems that don't\n          # expect these flags to be on. Automatically enables stuff like\n          # FORTIFY_SOURCE, -Werror=format-security, -fPIE, etc. See:\n          # - https://nixos.org/manual/nixpkgs/stable/#sec-hardening-in-nixpkgs\n          # - https://nixos.wiki/wiki/C#Hardening_flags\n          hardeningDisable = [ \"all\" ];\n          LD_LIBRARY_PATH = \"${pkgs.stdenv.cc.cc.lib.outPath}/lib:${pkgs.lib.makeLibraryPath rexPackages}:$LD_LIBRARY_PATH\";\n          shellHook = ''\n\n            export NIX_CC_WRAPPER_SUPPRESS_TARGET_WARNING=1\n            export PATH=$(realpath \"./build/rust-dist/bin\"):$PATH\n            # Add required llvm-config\n            export PATH=${patchedPkgs.llvmPackages.libllvm.out}/bin:$PATH\n            export PATH=${patchedPkgs.llvmPackages.libllvm.dev}/bin:$PATH\n            export RUST_BACKTRACE=1\n            export NIX_ENFORCE_NO_NATIVE=0\n            export LLVM_SRC_INC=\"$PWD/rust/src/llvm-project/llvm/include\"\n            # export LLVM_BUILD_INCLUDE=\"$PWD/build/rust-build/x86_64-unknown-linux-gnu/llvm/build/include\"\n            export NIX_CFLAGS_COMPILE_BEFORE=\"-I$LLVM_SRC_INC\"\n            echo \"loading rex env\"\n          '';\n        };\n      };\n\n      packages.\"${system}\" = {\n        fhsRex = fhsRex;\n        fhsExec = fhsExec;\n      };\n    };\n\n}\n"
  },
  {
    "path": "librex/.gitignore",
    "content": "librex.a\nlibrex.o\nlibrex.so\n.cache\n"
  },
  {
    "path": "librex/include/librex.h",
    "content": "#ifndef LIBREX_H\n#define LIBREX_H\n\nstruct bpf_object;\nstruct rex_obj;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n[[gnu::visibility(\"default\")]] void rex_set_debug(int val);\n\n[[nodiscard, gnu::visibility(\"default\")]] struct rex_obj *\nrex_obj_load(const char *file_path);\n\n[[nodiscard, gnu::visibility(\"default\")]] struct bpf_object *\nrex_obj_get_bpf(struct rex_obj *obj);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // LIBREX_H\n"
  },
  {
    "path": "librex/lib/bindings.h",
    "content": "// This file contains the non-portable part, it has to mirror some libbpf types\n\n#ifndef _LIBREX_BINDINGS_H\n#define _LIBREX_BINDINGS_H\n\n#include <bpf/libbpf.h>\n#include <gelf.h>\n\n/* From tools/lib/bpf/libbpf_internal.h */\n#define SHA256_DIGEST_LENGTH 32\n\nstruct elf_state {\n  int fd;\n  const void *obj_buf;\n  size_t obj_buf_sz;\n  Elf *elf;\n  Elf64_Ehdr *ehdr;\n  Elf_Data *symbols;\n  Elf_Data *arena_data;\n  size_t shstrndx; /* section index for section name strings */\n  size_t strtabidx;\n  struct elf_sec_desc *secs;\n  size_t sec_cnt;\n  int btf_maps_shndx;\n  __u32 btf_maps_sec_btf_id;\n  int text_shndx;\n  int symbols_shndx;\n  bool has_st_ops;\n  int arena_data_shndx;\n  int jumptables_data_shndx;\n};\n\nstruct bpf_sec_def {\n  char *sec;\n  enum bpf_prog_type prog_type;\n  enum bpf_attach_type expected_attach_type;\n  long cookie;\n  int handler_id;\n\n  libbpf_prog_setup_fn_t prog_setup_fn;\n  libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;\n  libbpf_prog_attach_fn_t prog_attach_fn;\n};\n\nenum bpf_object_state {\n  OBJ_OPEN,\n  OBJ_PREPARED,\n  OBJ_LOADED,\n};\n\nstruct bpf_object {\n  char name[BPF_OBJ_NAME_LEN];\n  char license[64];\n  __u32 kern_version;\n\n  enum bpf_object_state state;\n  struct bpf_program *programs;\n  size_t nr_programs;\n  struct bpf_map *maps;\n  size_t nr_maps;\n  size_t maps_cap;\n\n  char *kconfig;\n  struct extern_desc *externs;\n  int nr_extern;\n  int kconfig_map_idx;\n\n  bool has_subcalls;\n  bool has_rodata;\n\n  struct bpf_gen *gen_loader;\n\n  /* Information when doing ELF related work. Only valid if efile.elf is not\n   * NULL */\n  struct elf_state efile;\n\n  unsigned char byteorder;\n\n  struct btf *btf;\n  struct btf_ext *btf_ext;\n\n  /* Parse and load BTF vmlinux if any of the programs in the object need\n   * it at load time.\n   */\n  struct btf *btf_vmlinux;\n  /* Path to the custom BTF to be used for BPF CO-RE relocations as an\n   * override for vmlinux BTF.\n   */\n  char *btf_custom_path;\n  /* vmlinux BTF override for CO-RE relocations */\n  struct btf *btf_vmlinux_override;\n  /* Lazily initialized kernel module BTFs */\n  struct module_btf *btf_modules;\n  bool btf_modules_loaded;\n  size_t btf_module_cnt;\n  size_t btf_module_cap;\n\n  /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */\n  char *log_buf;\n  size_t log_size;\n  __u32 log_level;\n\n  int *fd_array;\n  size_t fd_array_cap;\n  size_t fd_array_cnt;\n\n  struct usdt_manager *usdt_man;\n\n  int arena_map_idx;\n  void *arena_data;\n  size_t arena_data_sz;\n\n  void *jumptables_data;\n  size_t jumptables_data_sz;\n\n  struct {\n    struct bpf_program *prog;\n    int sym_off;\n    int fd;\n  } *jumptable_maps;\n  size_t jumptable_map_cnt;\n\n  struct kern_feature_cache *feat_cache;\n  char *token_path;\n  int token_fd;\n\n  char path[];\n};\n\nstruct bpf_light_subprog;\n\n/*\n * bpf_prog should be a better name but it has been used in\n * linux/filter.h.\n */\nstruct bpf_program {\n  char *name;\n  char *sec_name;\n  size_t sec_idx;\n  const struct bpf_sec_def *sec_def;\n  /* this program's instruction offset (in number of instructions)\n   * within its containing ELF section\n   */\n  size_t sec_insn_off;\n  /* number of original instructions in ELF section belonging to this\n   * program, not taking into account subprogram instructions possible\n   * appended later during relocation\n   */\n  size_t sec_insn_cnt;\n  /* Offset (in number of instructions) of the start of instruction\n   * belonging to this BPF program  within its containing main BPF\n   * program. For the entry-point (main) BPF program, this is always\n   * zero. For a sub-program, this gets reset before each of main BPF\n   * programs are processed and relocated and is used to determined\n   * whether sub-program was already appended to the main program, and\n   * if yes, at which instruction offset.\n   */\n  size_t sub_insn_off;\n\n  /* instructions that belong to BPF program; insns[0] is located at\n   * sec_insn_off instruction within its ELF section in ELF file, so\n   * when mapping ELF file instruction index to the local instruction,\n   * one needs to subtract sec_insn_off; and vice versa.\n   */\n  struct bpf_insn *insns;\n  /* actual number of instruction in this BPF program's image; for\n   * entry-point BPF programs this includes the size of main program\n   * itself plus all the used sub-programs, appended at the end\n   */\n  size_t insns_cnt;\n\n  struct reloc_desc *reloc_desc;\n  int nr_reloc;\n\n  /* BPF verifier log settings */\n  char *log_buf;\n  size_t log_size;\n  __u32 log_level;\n\n  struct bpf_object *obj;\n\n  int fd;\n  bool autoload;\n  bool autoattach;\n  bool sym_global;\n  bool mark_btf_static;\n  enum bpf_prog_type type;\n  enum bpf_attach_type expected_attach_type;\n  int exception_cb_idx;\n\n  int prog_ifindex;\n  __u32 attach_btf_obj_fd;\n  __u32 attach_btf_id;\n  __u32 attach_prog_fd;\n\n  void *func_info;\n  __u32 func_info_rec_size;\n  __u32 func_info_cnt;\n\n  void *line_info;\n  __u32 line_info_rec_size;\n  __u32 line_info_cnt;\n  __u32 prog_flags;\n  __u8 hash[SHA256_DIGEST_LENGTH];\n\n  struct bpf_light_subprog *subprogs;\n  __u32 subprog_cnt;\n};\n\nenum libbpf_map_type {\n  LIBBPF_MAP_UNSPEC,\n  LIBBPF_MAP_DATA,\n  LIBBPF_MAP_BSS,\n  LIBBPF_MAP_RODATA,\n  LIBBPF_MAP_KCONFIG,\n};\n\nstruct bpf_map_def {\n  unsigned int type;\n  unsigned int key_size;\n  unsigned int value_size;\n  unsigned int max_entries;\n  unsigned int map_flags;\n};\n\nstruct bpf_map {\n  struct bpf_object *obj;\n  char *name;\n  /* real_name is defined for special internal maps (.rodata*,\n   * .data*, .bss, .kconfig) and preserves their original ELF section\n   * name. This is important to be able to find corresponding BTF\n   * DATASEC information.\n   */\n  char *real_name;\n  int fd;\n  int sec_idx;\n  size_t sec_offset;\n  int map_ifindex;\n  int inner_map_fd;\n  struct bpf_map_def def;\n  __u32 numa_node;\n  __u32 btf_var_idx;\n  int mod_btf_fd;\n  __u32 btf_key_type_id;\n  __u32 btf_value_type_id;\n  __u32 btf_vmlinux_value_type_id;\n  enum libbpf_map_type libbpf_type;\n  void *mmaped;\n  struct bpf_struct_ops *st_ops;\n  struct bpf_map *inner_map;\n  void **init_slots;\n  int init_slots_sz;\n  char *pin_path;\n  bool pinned;\n  bool reused;\n  bool autocreate;\n  bool autoattach;\n  __u64 map_extra;\n  struct bpf_program *excl_prog;\n};\n\n#endif // _LIBREX_BINDINGS_H\n"
  },
  {
    "path": "librex/lib/librex.cpp",
    "content": "#include <fcntl.h>\n#include <libelf.h>\n#include <linux/bpf.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n#include <algorithm>\n#include <cstdint>\n#include <cstring>\n#include <filesystem>\n#include <fstream>\n#include <iostream>\n#include <llvm/Demangle/Demangle.h>\n#include <memory>\n#include <optional>\n#include <ranges>\n#include <stdexcept>\n#include <string>\n#include <system_error>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"bindings.h\"\n#include \"librex.h\"\n\nusing namespace std::literals;\n\nnamespace {\n\nint debug = 0;\n\nbool sec_def_matches(const struct bpf_sec_def *sec_def,\n                     std::string_view sec_name) {\n  std::string_view sec_pfx(sec_def->sec);\n\n  // \"type/\" always has to have proper SEC(\"type/extras\") form\n  if (sec_pfx.back() == '/')\n    return sec_name.starts_with(sec_pfx);\n\n  // \"type+\" means it can be either exact SEC(\"type\") or\n  // well-formed SEC(\"type/extras\") with proper '/' separator\n  if (sec_pfx.back() == '+') {\n    size_t pfx_size;\n    sec_pfx.remove_suffix(1);\n    pfx_size = sec_pfx.size();\n\n    // not even a prefix\n    if (!sec_name.starts_with(sec_pfx))\n      return false;\n    // exact match or has '/' separator\n    return sec_name.size() == pfx_size || sec_name[pfx_size] == '/';\n  }\n\n  return sec_name == sec_pfx;\n}\n\n/// @brief Walk through the static const struct bpf_sec_def section_defs\n/// in libbpf.c and figure out the valid bpf section\n///\n/// @param sec_name section for our own rex prog\n/// @return section_defs\nconst bpf_sec_def *find_sec_def(std::string_view sec_name) {\n  for (size_t i = 0; i < global_bpf_section_defs.size; i++) {\n    if (!sec_def_matches(&global_bpf_section_defs.arr[i], sec_name))\n      continue;\n    return &global_bpf_section_defs.arr[i];\n  }\n\n  return nullptr;\n}\n\ninline long bpf(__u64 cmd, union bpf_attr *attr, unsigned int size) {\n  return syscall(__NR_bpf, cmd, attr, size);\n}\n\ninline uint64_t align_up_16(uint64_t val) {\n  return (val & 0xf) ? (val & ~0xf) + 0x10 : val;\n}\n\n} // end anonymous namespace\n\n// This struct is POD, meaning the C++ standard guarantees the same memory\n// layout as that of the equivalent C struct\n// https://stackoverflow.com/questions/422830/structure-of-a-c-object-in-memory-vs-a-struct\nstruct map_def {\n  uint32_t map_type;\n  uint32_t key_size;\n  uint32_t val_size;\n  uint32_t max_size;\n  uint32_t map_flag;\n  void *kptr;\n};\n\nstruct rex_map {\nprivate:\n  map_def def;\n  std::optional<int> map_fd;\n  std::string name;\n\npublic:\n  rex_map() = delete;\n  rex_map(const Elf_Data *data, Elf64_Addr base, Elf64_Off off,\n          const char *c_name)\n      : map_fd(), name(c_name) {\n    auto def_addr = reinterpret_cast<uint64_t>(data->d_buf) + off - base;\n    this->def = *reinterpret_cast<map_def *>(def_addr);\n\n    if (debug) {\n      std::clog << \"sym_name=\" << c_name << std::endl;\n      std::clog << \"map_type=\" << this->def.map_type << std::endl;\n      std::clog << \"key_size=\" << this->def.key_size << std::endl;\n      std::clog << \"val_size=\" << this->def.val_size << std::endl;\n      std::clog << \"max_size=\" << this->def.max_size << std::endl;\n      std::clog << \"map_flag=\" << this->def.map_flag << std::endl;\n    }\n  }\n\n  rex_map(const rex_map &) = delete;\n  rex_map(rex_map &&) = delete;\n\n  ~rex_map() {\n    map_fd.transform([](int fd) { return close(fd); });\n  }\n\n  rex_map &operator=(const rex_map &) = delete;\n  rex_map &operator=(rex_map &&) = delete;\n\n  std::optional<int> create() {\n    int ret;\n\n    union bpf_attr attr{\n        .map_type = def.map_type,\n        .key_size = def.key_size,\n        .value_size = def.val_size,\n        .max_entries = def.max_size,\n        .map_flags = def.map_flag,\n    };\n\n    memcpy(attr.map_name, name.c_str(),\n           std::min(name.size(), sizeof(attr.map_name) - 1));\n\n    ret = bpf(BPF_MAP_CREATE, &attr, sizeof(attr));\n    if (ret >= 0)\n      this->map_fd = ret;\n\n    return this->map_fd;\n  }\n\n  // rename bpf_map into bpfmap to avoid name collision\n  std::optional<bpf_map> bpfmap() {\n    // Do not create a bpf_map if the map has not been loaded\n    if (!map_fd)\n      return std::nullopt;\n\n    return bpf_map{\n        .name = name.data(),\n        .fd = map_fd.value(),\n        .inner_map_fd = -1,\n        .def =\n            {\n                .type = def.map_type,\n                .key_size = def.key_size,\n                .value_size = def.val_size,\n                .max_entries = def.max_size,\n                .map_flags = def.map_flag,\n            },\n        .libbpf_type = LIBBPF_MAP_UNSPEC,\n    };\n  }\n\n  friend struct ::rex_obj;\n};\n\nstruct rex_prog {\nprivate:\n  std::string name;\n  std::string scn_name;\n  const struct bpf_sec_def *sec_def;\n  Elf64_Off offset;\n  std::optional<int> prog_fd;\n\npublic:\n  rex_prog() = delete;\n  rex_prog(const char *nm, const char *scn_nm, Elf64_Off off)\n      : name(nm), scn_name(scn_nm), offset(off) {\n    sec_def = find_sec_def(scn_name);\n  }\n\n  rex_prog(const rex_prog &) = delete;\n\n  // std::optional only moves its underlying value and does not set the source\n  // object to std::nullopt. This prevents us from using a compiler-generated\n  // default implementation, because it would just copy the fd without\n  // invalidating afterwards (as int is trivially movable).\n  rex_prog(rex_prog &&other) noexcept\n      : name(std::move(other.name)), scn_name(std::move(other.scn_name)),\n        sec_def(std::move(other.sec_def)), offset(std::move(other.offset)),\n        prog_fd(std::move(other.prog_fd)) {\n    other.sec_def = nullptr;\n    other.offset = -1;\n    other.prog_fd = std::nullopt;\n  }\n\n  ~rex_prog() {\n    prog_fd.transform([](int fd) { return close(fd); });\n  }\n\n  rex_prog &operator=(const rex_prog &) = delete;\n  rex_prog &operator=(rex_prog &&) = delete;\n\n  std::optional<bpf_program> bpf_prog() {\n    // Do not create a bpf_program if the prog has not been loaded\n    if (!prog_fd)\n      return std::nullopt;\n\n    // bpf_program::obj will be initliazed by the caller\n    // bpf_program will never outlive \"this\" as both are managed by rex_obj,\n    // so just redirect pointers\n    return bpf_program{\n        .name = name.data(),\n        .sec_name = scn_name.data(),\n        .sec_idx = (size_t)-1,\n        .sec_def = sec_def,\n        .fd = prog_fd.value(),\n        .type = sec_def->prog_type,\n    };\n  }\n\n  friend struct ::rex_obj;\n};\n\nstruct rex_obj {\nprivate:\n  struct elf_del {\n    [[gnu::always_inline]] void operator()(Elf *ep) const { elf_end(ep); }\n  };\n\n  struct file_map_del {\n    size_t size;\n\n    file_map_del() = default;\n    explicit file_map_del(size_t sz) : size(sz) {}\n\n    [[gnu::always_inline]] void operator()(unsigned char *addr) const {\n      munmap(addr, size);\n    }\n  };\n\n  struct bpf_obj_del {\n    [[gnu::always_inline]] void operator()(bpf_object *bp) const {\n      delete[] bp->programs;\n      delete[] bp->maps;\n      delete bp;\n    }\n  };\n\n  std::vector<rex_prog> progs;\n  std::unordered_map<Elf64_Off, rex_map> map_defs;\n\n  std::unique_ptr<Elf, elf_del> elf;\n  Elf_Scn *symtab_scn;\n  Elf_Scn *dynsym_scn;\n  Elf_Scn *maps_scn;\n\n  // Global Offset Table for PIE\n  Elf_Scn *got_scn;\n\n  // Dynamic relocation for PIE\n  Elf_Scn *rela_dyn_scn;\n  std::vector<rex_rela_dyn> dyn_relas;\n  std::vector<rex_dyn_sym> dyn_syms;\n  std::vector<std::string> rela_sym_name;\n  std::optional<unsigned long> timeout_handler_off;\n  std::vector<std::tuple<std::string, uint64_t, uint64_t>> text_syms;\n\n  std::unique_ptr<unsigned char[], file_map_del> file_map;\n  std::optional<int> prog_fd;\n  bool loaded;\n  std::string basename;\n  std::unique_ptr<bpf_object, bpf_obj_del> bpf_obj_ptr;\n\n  int parse_scns();\n  int parse_maps();\n  int parse_progs();\n  int parse_got();\n  int parse_rela_dyn();\n\npublic:\n  rex_obj() = delete;\n  explicit rex_obj(const char *);\n  rex_obj(const rex_obj &) = delete;\n  rex_obj(rex_obj &&) = delete;\n  ~rex_obj();\n\n  rex_obj &operator=(const rex_obj &) = delete;\n  rex_obj &operator=(rex_obj &&) = delete;\n\n  int parse_elf();\n  int fix_maps();\n  int load();\n  bpf_object *bpf_obj();\n};\n\nrex_obj::rex_obj(const char *c_path)\n    : map_defs(), symtab_scn(nullptr), dynsym_scn(nullptr), maps_scn(nullptr),\n      prog_fd(-1), loaded(false) {\n  struct stat st;\n  void *mmap_ret;\n  int fd = open(c_path, 0, O_RDONLY);\n  Elf *ep = elf_begin(fd, ELF_C_READ_MMAP, NULL);\n  if (!ep)\n    throw std::invalid_argument(\"elf: failed to open file \"s + c_path);\n\n  elf = std::unique_ptr<Elf, elf_del>(ep, elf_del());\n\n  if (fstat(fd, &st) < 0)\n    throw std::system_error(errno, std::system_category(), \"fstat\");\n\n  // MAP_PRIVATE ensures the changes to the memory mapped by mmap(2) are not\n  // carried through to the backing file\n  mmap_ret = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);\n  if (mmap_ret == MAP_FAILED)\n    throw std::system_error(errno, std::system_category(), \"mmap\");\n\n  file_map = std::unique_ptr<unsigned char[], file_map_del>(\n      reinterpret_cast<unsigned char *>(mmap_ret), file_map_del(st.st_size));\n\n  std::string copy(c_path);\n  copy += \".base\";\n  basename = ::basename(copy.data());\n  close(fd);\n}\n\nrex_obj::~rex_obj() {\n  prog_fd.transform([](int fd) { return close(fd); });\n}\n\nint rex_obj::parse_scns() {\n  size_t shstrndx;\n\n  if (elf_getshdrstrndx(elf.get(), &shstrndx)) {\n    std::cerr << \"elf: failed to get section names section index for \"\n              << std::endl;\n    return -1;\n  }\n\n  for (auto scn = elf_nextscn(elf.get(), NULL); scn;\n       scn = elf_nextscn(elf.get(), scn)) {\n    char *name;\n    int idx = elf_ndxscn(scn);\n    Elf64_Shdr *sh = elf64_getshdr(scn);\n    if (!sh) {\n      std::cerr << \"elf: failed to get section header, idx=\" << idx\n                << std::endl;\n      return -1;\n    }\n\n    name = elf_strptr(elf.get(), shstrndx, sh->sh_name);\n\n    if (!name) {\n      std::cerr << \"elf: failed to get section name\" << std::endl;\n      return -1;\n    }\n\n    if (debug)\n      std::clog << \"section \" << name << \", idx=\" << idx << std::endl;\n\n    if (sh->sh_type == SHT_SYMTAB && !strcmp(\".symtab\", name))\n      this->symtab_scn = scn;\n    else if (sh->sh_type == SHT_DYNSYM && !strcmp(\".dynsym\", name))\n      this->dynsym_scn = scn;\n    else if (!strcmp(\".maps\", name))\n      this->maps_scn = scn;\n    else if (sh->sh_type == SHT_RELA && !strcmp(\".rela.dyn\", name))\n      this->rela_dyn_scn = scn;\n  }\n\n  if (!this->maps_scn && debug)\n    std::clog << \"section .maps not found\" << std::endl;\n\n  if (!this->rela_dyn_scn && debug)\n    std::clog << \"section .rela.dyn not found\" << std::endl;\n\n  return 0;\n}\n\nint rex_obj::parse_maps() {\n  Elf_Data *maps, *syms;\n  int nr_syms, nr_maps = 0, maps_shndx;\n  size_t strtabidx;\n  Elf64_Addr maps_shaddr;\n\n  if (!this->maps_scn)\n    return 0;\n\n  maps = elf_getdata(maps_scn, 0);\n  syms = elf_getdata(symtab_scn, 0);\n\n  if (!syms) {\n    std::cerr << \"elf: failed to get symbol definitions\" << std::endl;\n    return -1;\n  }\n\n  if (!maps) {\n    std::cerr << \"elf: failed to get map definitions\" << std::endl;\n    return -1;\n  }\n\n  strtabidx = elf64_getshdr(symtab_scn)->sh_link;\n  maps_shndx = elf_ndxscn(maps_scn);\n  maps_shaddr = elf64_getshdr(maps_scn)->sh_addr;\n  nr_syms = syms->d_size / sizeof(Elf64_Sym);\n\n  for (int i = 0; i < nr_syms; i++) {\n    Elf64_Sym *sym = reinterpret_cast<Elf64_Sym *>(syms->d_buf) + i;\n    char *name;\n\n    if (sym->st_shndx != maps_shndx ||\n        ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)\n      continue;\n\n    name = elf_strptr(elf.get(), strtabidx, sym->st_name);\n    if (debug) {\n      std::clog << \"symbol: \" << name << \", st_value=0x\" << std::hex\n                << sym->st_value << \", st_size=\" << std::dec << sym->st_size\n                << std::endl;\n    }\n\n    if (sym->st_size == sizeof(map_def)) {\n      map_defs.try_emplace(sym->st_value, maps, maps_shaddr, sym->st_value,\n                           name);\n    }\n\n    nr_maps++;\n  }\n\n  if (debug)\n    std::clog << \"# of symbols in \\\".maps\\\": \" << nr_maps << std::endl;\n\n  return 0;\n}\n\n// get sec name\n// get function symbols\nint rex_obj::parse_progs() {\n  size_t shstrndx, strtabidx;\n  Elf_Data *syms;\n  int nr_syms;\n\n  strtabidx = elf64_getshdr(symtab_scn)->sh_link;\n\n  if (elf_getshdrstrndx(elf.get(), &shstrndx)) {\n    std::cerr << \"elf: failed to get section names section index\" << std::endl;\n    return -1;\n  }\n\n  syms = elf_getdata(symtab_scn, 0);\n\n  if (!syms) {\n    std::cerr << \"elf: failed to get symbol definitions\" << std::endl;\n    return -1;\n  }\n\n  nr_syms = syms->d_size / sizeof(Elf64_Sym);\n\n  for (int i = 0; i < nr_syms; i++) {\n    Elf64_Sym *sym = reinterpret_cast<Elf64_Sym *>(syms->d_buf) + i;\n    Elf_Scn *scn = elf_getscn(elf.get(), sym->st_shndx);\n    char *scn_name, *sym_name;\n    const bpf_sec_def *sec_def;\n\n    if (!scn || ELF64_ST_TYPE(sym->st_info) != STT_FUNC)\n      continue;\n\n    scn_name = elf_strptr(elf.get(), shstrndx, elf64_getshdr(scn)->sh_name);\n    sym_name = elf_strptr(elf.get(), strtabidx, sym->st_name);\n\n    if (sym->st_value) {\n      // Align symbol size up to 16-byte boundary, which is the default function\n      // alignment in x86-64, to account for trailing nops\n      text_syms.emplace_back(llvm::demangle(sym_name), sym->st_value,\n                             align_up_16(sym->st_size));\n    }\n\n    if (\"__rex_handle_timeout\"sv == sym_name)\n      timeout_handler_off = sym->st_value;\n\n    if (debug) {\n      std::clog << \"symbol: \\\"\" << sym_name << \"\\\"\" << \", section: \\\"\"\n                << scn_name << \"\\\"\" << \", st_value=0x\" << std::hex\n                << sym->st_value << \", st_size=\" << sym->st_size << std::dec\n                << std::endl;\n    }\n\n    sec_def = find_sec_def(scn_name);\n    if (!sec_def)\n      continue;\n\n    if (debug)\n      std::clog << \"successfully matched\" << std::endl;\n\n    sym_name = elf_strptr(elf.get(), strtabidx, sym->st_name);\n    progs.emplace_back(sym_name, scn_name, sym->st_value);\n  }\n\n  if (!timeout_handler_off) {\n    std::cerr << \"elf: __rex_handle_timeout not found\" << std::endl;\n    return -1;\n  }\n\n  if (debug) {\n    std::clog << \"Found __rex_handle_timeout at offset\" << std::hex\n              << timeout_handler_off.value() << std::dec << std::endl;\n  }\n\n  return 0;\n};\n\nint rex_obj::parse_rela_dyn() {\n  Elf64_Shdr *rela_dyn;\n  rex_rela_dyn *rela_dyn_data;\n  uint64_t rela_dyn_addr, rela_dyn_size, nr_dyn_relas;\n  size_t idx;\n\n  if (!this->rela_dyn_scn)\n    return 0;\n\n  rela_dyn = elf64_getshdr(rela_dyn_scn);\n\n  if (!rela_dyn) {\n    std::cerr << \"elf: failed to get .rela.dyn section\" << std::endl;\n    return -1;\n  }\n\n  rela_dyn_data =\n      reinterpret_cast<rex_rela_dyn *>(elf_getdata(rela_dyn_scn, 0)->d_buf);\n  rela_dyn_addr = rela_dyn->sh_addr;\n  rela_dyn_size = rela_dyn->sh_size;\n\n  if (debug) {\n    std::clog << \".rela.dyn offset=\" << std::hex << rela_dyn_addr\n              << \", .rela.dyn size=\" << std::dec << rela_dyn_size << std::endl;\n  }\n\n  if (rela_dyn_size % sizeof(rex_rela_dyn)) {\n    std::cerr << \"elf: ill-formed .rela.dyn section\" << std::endl;\n    return -1;\n  }\n\n  nr_dyn_relas = rela_dyn_size / sizeof(rex_rela_dyn);\n\n  for (idx = 0; idx < nr_dyn_relas; idx++) {\n    if (ELF64_R_TYPE(rela_dyn_data[idx].info) == R_X86_64_RELATIVE) {\n      dyn_relas.push_back(rela_dyn_data[idx]);\n    } else if (ELF64_R_TYPE(rela_dyn_data[idx].info) == R_X86_64_GLOB_DAT) {\n      uint32_t dynsym_idx = ELF64_R_SYM(rela_dyn_data[idx].info);\n      Elf_Data *syms = elf_getdata(dynsym_scn, 0);\n      size_t strtabidx = elf64_getshdr(dynsym_scn)->sh_link;\n      Elf64_Sym *sym = reinterpret_cast<Elf64_Sym *>(syms->d_buf) + dynsym_idx;\n      rex_dyn_sym dyn_sym = {};\n      char *name = elf_strptr(elf.get(), strtabidx, sym->st_name);\n\n      dyn_sym.offset = rela_dyn_data[idx].offset;\n      dyn_sym.symbol = name;\n\n      dyn_syms.push_back(dyn_sym);\n    } else {\n      std::cerr << \"elf: relocation type not supported\" << std::endl;\n      return -1;\n    }\n  }\n\n  if (debug) {\n    std::clog << \".rela.dyn: \" << std::hex << std::endl;\n    for (auto &dyn_rela : dyn_relas) {\n      std::clog << \"0x\" << dyn_rela.offset << \", 0x\" << dyn_rela.info << \", 0x\"\n                << dyn_rela.addend << std::endl;\n    }\n    for (auto &dyn_sym : dyn_syms) {\n      std::clog << \"0x\" << dyn_sym.offset << \", \" << dyn_sym.symbol\n                << std::endl;\n    }\n    std::clog << std::dec;\n  }\n\n  return 0;\n}\n\nint rex_obj::parse_elf() {\n  int ret;\n\n  if (!elf) {\n    std::cerr << \"elf: failed to open object\" << std::endl;\n    return -1;\n  }\n\n  ret = this->parse_scns();\n  ret = ret < 0 ? ret : this->parse_maps();\n  ret = ret < 0 ? ret : this->parse_progs();\n  ret = ret < 0 ? ret : this->parse_rela_dyn();\n\n  return ret;\n}\n\nint rex_obj::fix_maps() {\n  Elf64_Addr maps_shaddr;\n  Elf64_Off maps_shoff;\n\n  if (!this->maps_scn) {\n    return 0;\n  }\n\n  maps_shaddr = elf64_getshdr(maps_scn)->sh_addr;\n  maps_shoff = elf64_getshdr(maps_scn)->sh_offset;\n\n  if (debug) {\n    std::clog << \".maps section file offset=0x\" << std::hex\n              << elf64_getshdr(maps_scn)->sh_offset << std::dec << std::endl;\n  }\n\n  for (auto &[m_off, m_def] : map_defs) {\n    size_t kptr_file_off =\n        m_off + offsetof(map_def, kptr) - maps_shaddr + maps_shoff;\n\n    if (debug) {\n      std::clog << \"map_ptr=0x\" << std::hex << m_off << std::dec << std::endl;\n      std::clog << \"map_name=\\\"\" << m_def.name << '\\\"' << std::endl;\n    }\n\n    std::optional<int> map_fd = m_def.create();\n    if (!map_fd) {\n      perror(\"bpf_map_create\");\n      return -1;\n    }\n\n    if (debug)\n      std::clog << \"map_fd=\" << map_fd.value() << std::endl;\n\n    *reinterpret_cast<uint64_t *>(&this->file_map[kptr_file_off]) =\n        map_fd.value();\n  }\n\n  return 0;\n}\n\nint rex_obj::load() {\n  int fd;\n  auto arr = std::make_unique<uint64_t[]>(map_defs.size());\n  union bpf_attr attr = {};\n  int idx = 0, ret = 0;\n  std::filesystem::path tmp_file = \"/tmp/rex-\" + std::to_string(gettid());\n  std::unique_ptr<rex_text_sym[]> tsym_arr(new rex_text_sym[text_syms.size()]);\n\n  // TODO: Will have race condition if multiple objs loaded at same time\n  std::ofstream output(tmp_file, std::ios::out | std::ios::binary);\n\n  output.write((char *)this->file_map.get(), this->file_map.get_deleter().size);\n  output.close();\n\n  fd = open(tmp_file.c_str(), O_RDONLY);\n\n  for (auto &def : map_defs)\n    arr[idx++] = def.first + offsetof(map_def, kptr);\n\n  attr.prog_type = BPF_PROG_TYPE_REX_BASE;\n  // progname was zero-initialized so we don't copy the null terminator\n  memcpy(attr.prog_name, basename.c_str(),\n         std::min(basename.size(), sizeof(attr.prog_name) - 1));\n  attr.rustfd = fd;\n  attr.license = reinterpret_cast<__u64>(\"GPL\");\n\n  attr.map_offs = reinterpret_cast<__u64>(arr.get());\n  attr.map_cnt = map_defs.size();\n\n  attr.dyn_relas = reinterpret_cast<__u64>(dyn_relas.data());\n  attr.nr_dyn_relas = dyn_relas.size();\n\n  attr.dyn_syms = reinterpret_cast<__u64>(dyn_syms.data());\n  attr.nr_dyn_syms = dyn_syms.size();\n\n  // Copy data into the array that will be sent to the kernel\n  for (const auto &[idx, sym] : std::views::enumerate(text_syms)) {\n    tsym_arr[idx].symbol = std::get<0>(sym).c_str();\n    std::tie(std::ignore, tsym_arr[idx].offset, tsym_arr[idx].size) = sym;\n  }\n\n  attr.text_syms = reinterpret_cast<__u64>(tsym_arr.get());\n  attr.nr_text_syms = text_syms.size();\n\n  ret = bpf(BPF_PROG_LOAD_REX_BASE, &attr, sizeof(attr));\n\n  if (ret < 0) {\n    perror(\"bpf_prog_load_rex_base\");\n    return -1;\n  }\n\n  this->prog_fd = ret;\n\n  if (debug)\n    std::clog << \"Base program loaded, fd = \" << ret << std::endl;\n\n  close(fd);\n  if (!std::filesystem::remove(tmp_file)) {\n    perror(\"remove\");\n    goto close_fds;\n  }\n\n  for (auto &prog : progs) {\n    int curr_fd;\n    attr.prog_type = prog.sec_def->prog_type;\n    strncpy(attr.prog_name, prog.name.c_str(), sizeof(attr.prog_name) - 1);\n    attr.base_prog_fd = this->prog_fd.value();\n    attr.prog_offset = prog.offset;\n    attr.license = (__u64) \"GPL\";\n    attr.unwinder_insn_off = timeout_handler_off.value();\n    curr_fd = bpf(BPF_PROG_LOAD_REX, &attr, sizeof(attr));\n\n    if (curr_fd < 0) {\n      perror(\"bpf_prog_load_rex\");\n      goto close_fds;\n    }\n\n    prog.prog_fd = curr_fd;\n\n    if (debug)\n      std::clog << \"Program \" << prog.name\n                << \" loaded, fd = \" << prog.prog_fd.value_or(-1) << std::endl;\n  }\n\n  loaded = true;\n  return ret;\n\nclose_fds:\n  for (auto &prog : progs) {\n    prog.prog_fd = prog.prog_fd.and_then([](int fd) -> std::optional<int> {\n      close(fd);\n      return std::nullopt;\n    });\n  }\n  prog_fd = prog_fd.and_then([](int fd) -> std::optional<int> {\n    close(fd);\n    return std::nullopt;\n  });\n  return -1;\n}\n\nbpf_object *rex_obj::bpf_obj() {\n  size_t i;\n  // Do not create a bpf_object if the obj has not been loaded\n  if (!loaded)\n    return nullptr;\n\n  // Return the previously created ptr\n  if (bpf_obj_ptr)\n    return bpf_obj_ptr.get();\n\n  // Create a new ptr\n  decltype(bpf_obj_ptr) ptr(new bpf_object, bpf_obj_del());\n  ptr->maps = new bpf_map[map_defs.size()];\n  ptr->programs = new bpf_program[progs.size()];\n\n  // Fill in maps\n  i = 0;\n  for (auto &[_, m_def] : map_defs) {\n    if (std::optional<bpf_map> map = m_def.bpfmap()) {\n      ptr->maps[i] = std::move(map.value());\n      ptr->maps[i++].obj = ptr.get();\n    } else {\n      return nullptr;\n    }\n  }\n  ptr->nr_maps = i;\n\n  // Fill in programs\n  i = 0;\n  for (auto &prog : progs) {\n    if (std::optional<bpf_program> bpf_prog = prog.bpf_prog()) {\n      ptr->programs[i] = std::move(bpf_prog.value());\n      ptr->programs[i].obj = ptr.get();\n      i++;\n    } else {\n      return nullptr;\n    }\n  }\n  ptr->nr_programs = i;\n  ptr->state = OBJ_LOADED;\n\n  // Now transfer the ownership\n  bpf_obj_ptr = std::move(ptr);\n\n  return bpf_obj_ptr.get();\n}\n\n[[gnu::visibility(\"default\")]] void rex_set_debug(int val) { debug = val; }\n\nstatic std::vector<std::unique_ptr<rex_obj>> objs;\n\n[[nodiscard, gnu::visibility(\"default\")]] rex_obj *\nrex_obj_load(const char *file_path) {\n  int ret;\n  if (elf_version(EV_CURRENT) == EV_NONE) {\n    std::cerr << \"elf: failed to init libelf\" << std::endl;\n    return nullptr;\n  }\n\n  try {\n    auto obj = std::make_unique<rex_obj>(file_path);\n    ret = obj->parse_elf();\n    ret = ret ? ret : obj->fix_maps();\n    ret = ret ? ret : obj->load();\n\n    if (ret >= 0) {\n      objs.push_back(std::move(obj));\n      return objs.back().get();\n    } else {\n      return nullptr;\n    }\n\n  } catch (std::exception &e) {\n    std::cerr << e.what() << std::endl;\n    return nullptr;\n  }\n}\n\n[[nodiscard, gnu::visibility(\"default\")]] bpf_object *\nrex_obj_get_bpf(rex_obj *obj) {\n  try {\n    return obj->bpf_obj();\n  } catch (std::exception &e) {\n    std::cerr << e.what() << std::endl;\n    return nullptr;\n  }\n}\n"
  },
  {
    "path": "librex/meson.build",
    "content": "rex_rootdir = '..'\n\nllvm_dep = dependency('llvm', version : '>=18')\nelf_dep = dependency('libelf')\n\nlibrex_public_inc = include_directories('include')\n\nlibrex_sources = [\n  'lib/librex.cpp'\n]\n\nlibrex = library(\n  'rex',\n  librex_sources,\n  cpp_args: ['-Wno-missing-designated-field-initializers'],\n  build_rpath: join_paths(meson.project_source_root(), 'linux/tools/lib/bpf'),\n  build_by_default: false,\n  dependencies: [elf_dep, llvm_dep, kernel_dep, libbpf_dep],\n  gnu_symbol_visibility: 'hidden',\n  include_directories: librex_public_inc,\n  pic: true\n)\n\nlibrex_dep = declare_dependency(\n  link_with: librex,\n  include_directories: librex_public_inc\n)\n"
  },
  {
    "path": "meson.build",
    "content": "project('rex-compile',\n  ['c', 'cpp'],\n  version: '0.1.0',\n  default_options : [\n    'buildtype=debugoptimized',\n    'warning_level=2',\n    'werror=true',\n    'b_lto=true',\n    'b_lto_mode=thin',\n    'b_pie=true',\n    'c_std=gnu23',\n    'cpp_std=c++23'\n  ]\n)\n\nadd_project_arguments(\n  [\n    '-pipe',\n    '-march=native',\n    '-ffunction-sections',\n    '-fdata-sections',\n    '-fno-semantic-interposition'\n  ],\n  language: ['c', 'cpp']\n)\n\nadd_project_link_arguments(\n  [\n    '-Wl,-O1',\n    '-Wl,--gc-sections',\n    '-Wl,-z,now',\n    '-Wl,-z,relro'\n  ],\n  language: ['c', 'cpp']\n)\n\nbindgen = find_program('bindgen')\ncmake = find_program('cmake')\nninja = find_program('ninja')\nperl = find_program('perl')\npython3_bin = find_program('python3', version: '>=3.11')\nrealpath = find_program('realpath')\nlld = find_program('ld.lld')\nbc = find_program('bc')\nflex = find_program('flex')\nbison = find_program('bison')\n\nsubdir('linux')\nsubdir('librex')\n\nrust_bootstrap_config = files('./rust/rex-config.toml')\nrust_bootstrap = custom_target(\n  'rust',\n  output : ['cargo', 'rustc'],\n  command: [\n    python3_bin, '@SOURCE_ROOT@/rust/x.py', 'install',\n    '--config=@SOURCE_ROOT@/rust/rex-config.toml',\n    '--build-dir=@OUTDIR@/rust-build',\n    '--set', 'install.prefix=@OUTDIR@/rust-dist'\n  ],\n  console: true,\n  build_by_default: false,\n  env: ['RUSTFLAGS=-C link-arg=-fuse-ld=mold']\n)\n\nall_programs = custom_target('build_deps',\n    output: ['kernel', 'kernel_libbpf', 'rust'],\n    command: ['echo', 'Build all depends'],\n    depends: [kernel_build, kernel_libbpf, rust_bootstrap],\n    console: true\n)\n\nrust_bin = join_paths(meson.current_build_dir(), 'rust-dist/bin')\ncargo_wrapper = join_paths(meson.project_source_root(), 'scripts/cargo-wrapper.pl')\nsanity_test_scripts = join_paths(meson.project_source_root(), 'scripts/sanity_tests/run_tests.py')\n\nruntest_deps = []\n\nsubdir('samples')\nsubdir('rex')\n"
  },
  {
    "path": "rex/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "rex/.gitignore",
    "content": "Cargo.lock\ntarget\nlibiustub/libiustub.so\n"
  },
  {
    "path": "rex/Cargo.toml",
    "content": "[package]\nname = \"rex\"\nversion = \"0.2.0\"\nbuild = \"build.rs\"\nautotests = false\nrepository.workspace = true\nedition.workspace = true\nauthors.workspace = true\n\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[lib]\ntest = false\ndoctest = false\n\n[dependencies]\npaste = { workspace = true }\nrex-macros = { workspace = true }\n\n[features]\ndefault = [\"debug_printk\"]\ndebug_printk = []\n\n[rex]\nuheaders = [\n  \"linux/bpf.h\",\n  \"linux/errno.h\",\n  \"linux/in.h\",\n  \"linux/perf_event.h\",\n  \"linux/pkt_cls.h\",\n  \"linux/ptrace.h\",\n  \"linux/seccomp.h\",\n  \"linux/unistd.h\",\n]\n\nkheaders = [\n  \"linux/filter.h\",\n  \"linux/gfp_types.h\",\n  \"linux/if_ether.h\",\n  \"linux/ip.h\",\n  \"linux/kcsan.h\",\n  \"linux/perf_event.h\",\n  \"linux/prandom.h\",\n  \"linux/sched.h\",\n  \"linux/seqlock.h\",\n  \"linux/skbuff.h\",\n  \"linux/tcp.h\",\n  \"linux/timekeeper_internal.h\",\n  \"linux/udp.h\",\n  \"net/xdp.h\",\n]\n\nkconfigs = [\"CONFIG_BPF_KPROBE_OVERRIDE\", \"CONFIG_KALLSYMS_ALL\"]\n"
  },
  {
    "path": "rex/build.py",
    "content": "import os\nimport re\nimport subprocess\nimport sys\nimport tomllib\n\n# https://github.com/rust-lang/rust-bindgen\nbindgen_cmd = '''bindgen $LINUX_OBJ/usr/include/%s --use-core\n--with-derive-default --ctypes-prefix core::ffi --no-layout-tests\n--no-debug '.*' --no-doc-comments --rust-target=1.85.0 --rust-edition=2024\n--translate-enum-integer-types --no-prepend-enum-name --blocklist-type\npt_regs --wrap-unsafe-ops -o %s -- -I$LINUX_OBJ/usr/include'''\n\nk_structs = ['task_struct', 'tk_read_base', 'seqcount_raw_spinlock_t',\n             'clocksource', 'seqcount_t', 'seqcount_latch_t', 'timekeeper',\n             'kcsan_ctx', 'rnd_state', 'timespec64', 'bpf_spin_lock',\n             'bpf_sysctl_kern', 'xdp_buff', 'ethhdr', 'iphdr', 'tcphdr',\n             'udphdr', 'sk_buff', 'sock', 'pcpu_hot',\n             'bpf_perf_event_data_kern']\n\nbindgen_kernel_cmd = '''bindgen %s --allowlist-type=\"%s\"\n--allowlist-var=\"(___GFP.*|CONFIG_.*|MAX_BPRINTF_BUF)\"\n--opaque-type xregs_state\n--opaque-type desc_struct --opaque-type arch_lbr_state --opaque-type\nlocal_apic --opaque-type alt_instr --opaque-type x86_msi_data --opaque-type\nx86_msi_addr_lo --opaque-type kunit_try_catch --opaque-type spinlock\n--no-doc-comments --blocklist-function __list_.*_report --use-core\n--with-derive-default --ctypes-prefix core::ffi --no-layout-tests\n--no-debug '.*' --rust-target=1.85.0 --rust-edition=2024 --wrap-unsafe-ops\n-o %s -- -nostdinc -I$LINUX_SRC/arch/x86/include\n-I$LINUX_OBJ/arch/x86/include/generated\n-I$LINUX_SRC/include -I$LINUX_SRC/arch/x86/include/uapi\n-I$LINUX_OBJ/arch/x86/include/generated/uapi -I$LINUX_SRC/include/uapi\n-I$LINUX_OBJ/include\n-I$LINUX_OBJ/include/generated/uapi -include\n$LINUX_SRC/include/linux/compiler-version.h -include\n$LINUX_SRC/include/linux/kconfig.h -include\n$LINUX_SRC/include/linux/compiler_types.h -D__KERNEL__\n--target=x86_64-linux-gnu -fintegrated-as -Werror=unknown-warning-option\n-Werror=ignored-optimization-argument -Werror=option-ignored\n-Werror=unused-command-line-argument -fmacro-prefix-map=./= -std=gnu11\n-fshort-wchar -funsigned-char -fno-common -fno-PIE -fno-strict-aliasing\n-mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx -fcf-protection=branch\n-fno-jump-tables -m64 -falign-loops=1 -mno-80387 -mno-fp-ret-in-387\n-mstack-alignment=8 -mskip-rax-setup -mtune=generic -mno-red-zone\n-mcmodel=kernel -Wno-sign-compare -fno-asynchronous-unwind-tables\n-fno-delete-null-pointer-checks -O2 -fstack-protector-strong\n-fno-stack-clash-protection -pg -mfentry -DCC_USING_NOP_MCOUNT\n-DCC_USING_FENTRY -fno-lto -falign-functions=16 -fstrict-flex-arrays=3\n-fms-extensions -fno-strict-overflow -fno-stack-check -Wall -Wundef\n-Werror=implicit-function-declaration -Werror=implicit-int\n-Werror=return-type -Werror=strict-prototypes -Wno-format-security\n-Wno-trigraphs -Wno-frame-address -Wno-address-of-packed-member\n-Wmissing-declarations -Wmissing-prototypes -Wframe-larger-than=2048\n-Wno-gnu -Wno-microsoft-anon-tag -Wvla -Wno-pointer-sign -Wcast-function-type\n-Wimplicit-fallthrough -Werror=date-time -Werror=incompatible-pointer-types\n-Wenum-conversion -Wextra -Wunused -Wno-unused-but-set-variable\n-Wno-unused-const-variable -Wno-format-overflow\n-Wno-format-overflow-non-kprintf -Wno-format-truncation-non-kprintf\n-Wno-override-init -Wno-pointer-to-enum-cast\n-Wno-tautological-constant-out-of-range-compare -Wno-unaligned-access\n-Wno-enum-compare-conditional -Wno-enum-enum-conversion\n-Wno-missing-field-initializers -Wno-type-limits -Wno-shift-negative-value\n-Wno-sign-compare -Wno-unused-parameter -g\n-DKBUILD_MODFILE='\"rex/rex_generated\"' -DKBUILD_BASENAME='\"rex_generated\"'\n-DKBUILD_MODNAME='\"rex_generated\"' -D__KBUILD_MODNAME=kmod_rex_generated\n-D__BINDGEN__ -DMODULE'''\n\n\ndef prep_uapi_headers(linux_path, headers, out_dir):\n    for header in headers:\n        subdir, hfile = os.path.split(header)\n        subdir = os.path.join(out_dir, subdir)\n        if not os.path.exists(subdir):\n            os.makedirs(subdir)\n\n        out_f = os.path.join(subdir, '%s.rs' % os.path.splitext(hfile)[0])\n        cmd = bindgen_cmd.replace('\\n', ' ').replace('$LINUX_OBJ', linux_path)\n        subprocess.run(cmd % (header, out_f), check=True, shell=True)\n\n\ndef parse_cargo_toml(cargo_toml_path):\n    with open(cargo_toml_path, 'rb') as toml_f:\n        cargo_toml = tomllib.load(toml_f)\n\n    uheaders = cargo_toml['rex'].get('uheaders', [])\n    kheaders = cargo_toml['rex'].get('kheaders', [])\n    kconfigs = cargo_toml['rex'].get('kconfigs', [])\n\n    return uheaders, kheaders, kconfigs\n\n\ndef prep_kernel_headers(headers, linux_src, linux_obj, out_dir):\n    bindings_h = os.path.join(out_dir, 'bindings.h')\n    out_subdir = os.path.join(out_dir, 'linux')\n    if not os.path.exists(out_subdir):\n        os.makedirs(out_subdir)\n    kernel_rs = os.path.join(out_subdir, 'kernel.rs')\n\n    with open(bindings_h, 'w') as bindings:\n        for h in headers:\n            bindings.write('#include <%s>\\n' % h)\n\n    cmd = (\n        bindgen_kernel_cmd.replace(\"\\n\", \" \")\n        .replace(\"$LINUX_SRC\", linux_src)\n        .replace(\"$LINUX_OBJ\", linux_obj)\n    )\n    subprocess.run(\n        cmd % (bindings_h, \"|\".join(k_structs), kernel_rs), check=True, shell=True\n    )\n\n\ndef parse_kconfigs(dot_config_path, kconfigs):\n    if len(kconfigs) == 0:\n        return\n\n    with open(dot_config_path) as dot_config:\n        dot_config_content = dot_config.readlines()\n\n    ptn = re.compile('(%s)' % '|'.join(kconfigs))\n\n    fmt = 'cargo:rustc-cfg=%s=\"%s\"\\n' + \\\n          'cargo::rustc-check-cfg=cfg(%s, values(\"%s\"))'\n\n    print('\\n'.join(map(lambda l: fmt % (l * 2),\n                        map(lambda l: tuple(l.strip().split('=')),\n                            filter(lambda l: l[0] != '#' and ptn.match(l),\n                                   dot_config_content)))))\n\n\ndef main(argv):\n    linux_obj = argv[1]\n    linux_src = argv[2]\n    out_dir = argv[3]\n    target_path = os.getcwd()\n\n    result = parse_cargo_toml(os.path.join(target_path, 'Cargo.toml'))\n    uheaders, kheaders, kconfigs = result\n\n    u_out_dir = os.path.join(out_dir, 'uapi')\n    prep_uapi_headers(linux_obj, uheaders, u_out_dir)\n    prep_kernel_headers(kheaders, linux_src, linux_obj, out_dir)\n    parse_kconfigs(os.path.join(linux_obj, '.config'), kconfigs)\n    return 0\n\n\nif __name__ == '__main__':\n    exit(main(sys.argv))\n"
  },
  {
    "path": "rex/build.rs",
    "content": "#![feature(exit_status_error)]\n\nuse std::io::Result;\nuse std::path::Path;\nuse std::process::Command;\nuse std::string::String;\nuse std::{env, fs};\n\nfn main() -> Result<()> {\n    let out_dir = env::var(\"OUT_DIR\").unwrap();\n    let linux_obj = env::var(\"LINUX_OBJ\").unwrap();\n    let linux_src = env::var(\"LINUX_SRC\").unwrap();\n\n    let output = Command::new(\"python3\")\n        .arg(\"build.py\")\n        .arg(&linux_obj)\n        .arg(&linux_src)\n        .arg(&out_dir)\n        .output()?;\n\n    output\n        .status\n        .exit_ok()\n        .map(|_| print!(\"{}\", String::from_utf8_lossy(&output.stdout)))\n        .map_err(|_| panic!(\"\\n{}\", String::from_utf8_lossy(&output.stderr)))\n        .unwrap();\n\n    let mut rexstub_outdir = Path::new(&out_dir).join(\"librexstub\");\n    if !rexstub_outdir.exists() {\n        fs::create_dir(&rexstub_outdir)?;\n    }\n\n    let rexstub_so = rexstub_outdir.join(\"librexstub.so\");\n    Command::new(\"clang\")\n        .arg(\"-fPIC\")\n        .arg(\"-nostartfiles\")\n        .arg(\"-nodefaultlibs\")\n        .arg(\"--shared\")\n        .arg(\"-o\")\n        .arg(rexstub_so.to_string_lossy().to_mut())\n        .arg(\"./librexstub/lib.c\")\n        .output()?;\n\n    rexstub_outdir = rexstub_outdir.canonicalize()?;\n\n    println!(\"cargo:rerun-if-changed=Cargo.toml\");\n    println!(\"cargo:rerun-if-changed=./src/*\");\n    println!(\"cargo:rerun-if-changed=./librexstub/*\");\n    println!(\"cargo:rustc-link-lib=dylib=rexstub\");\n    println!(\n        \"cargo:rustc-link-search=native={}\",\n        rexstub_outdir.to_string_lossy()\n    );\n\n    Ok(())\n}\n"
  },
  {
    "path": "rex/librexstub/lib.c",
    "content": "// Functions\n#define KSYM_FUNC(func) \\\n  int func() { return 0; }\n\nKSYM_FUNC(bpf_get_current_pid_tgid)\nKSYM_FUNC(bpf_trace_printk)\nKSYM_FUNC(bpf_map_lookup_elem)\nKSYM_FUNC(bpf_map_update_elem)\nKSYM_FUNC(bpf_map_delete_elem)\nKSYM_FUNC(bpf_map_push_elem)\nKSYM_FUNC(bpf_map_pop_elem)\nKSYM_FUNC(bpf_map_peek_elem)\nKSYM_FUNC(bpf_probe_read_kernel)\nKSYM_FUNC(ktime_get_mono_fast_ns)\nKSYM_FUNC(ktime_get_boot_fast_ns)\nKSYM_FUNC(get_random_u32)\nKSYM_FUNC(bpf_snprintf)\nKSYM_FUNC(vprintk)\nKSYM_FUNC(rex_landingpad)\nKSYM_FUNC(bpf_spin_lock)\nKSYM_FUNC(bpf_spin_unlock)\nKSYM_FUNC(just_return_func)\nKSYM_FUNC(bpf_get_stackid_pe)\nKSYM_FUNC(bpf_perf_prog_read_value)\nKSYM_FUNC(bpf_perf_event_output_tp)\nKSYM_FUNC(bpf_perf_event_read_value)\nKSYM_FUNC(bpf_skb_event_output)\nKSYM_FUNC(bpf_xdp_event_output)\nKSYM_FUNC(bpf_xdp_adjust_head)\nKSYM_FUNC(bpf_xdp_adjust_tail)\nKSYM_FUNC(bpf_clone_redirect)\nKSYM_FUNC(bpf_ringbuf_output)\nKSYM_FUNC(bpf_ringbuf_reserve)\nKSYM_FUNC(bpf_ringbuf_submit)\nKSYM_FUNC(bpf_ringbuf_discard)\nKSYM_FUNC(bpf_ringbuf_query)\nKSYM_FUNC(bpf_ktime_get_ns)\nKSYM_FUNC(bpf_ktime_get_boot_ns)\nKSYM_FUNC(bpf_ktime_get_coarse_ns)\nKSYM_FUNC(rex_trace_printk)\nKSYM_FUNC(bpf_task_from_pid)\nKSYM_FUNC(bpf_task_release)\n\n// Global variables\nunsigned long jiffies;\nint numa_node;\nvoid *rex_cleanup_entries;\nunsigned long rex_stack_ptr;\nvoid *current_task;\nint cpu_number;\nunsigned char rex_termination_state;\nunsigned long this_cpu_off;\nchar *rex_log_buf;\n"
  },
  {
    "path": "rex/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nrex_build = custom_target(\n  'rex-build',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  env: env,\n  console: false,\n  build_always_stale: true,\n  build_by_default: false\n)\n"
  },
  {
    "path": "rex/src/base_helper.rs",
    "content": "// use crate::timekeeping::*;\nuse core::intrinsics::unlikely;\nuse core::mem::MaybeUninit;\n\nuse crate::ffi;\nuse crate::linux::bpf::bpf_map_type;\nuse crate::linux::errno::EINVAL;\nuse crate::map::*;\nuse crate::per_cpu::this_cpu_read;\nuse crate::random32::bpf_user_rnd_u32;\nuse crate::utils::{to_result, NoRef, Result};\n\nmacro_rules! termination_check {\n    ($func:expr) => {{\n        // Declare and initialize the termination flag pointer\n        let termination_flag: *mut u8;\n        unsafe {\n            termination_flag = crate::per_cpu::this_cpu_ptr_mut(\n                &raw mut crate::ffi::rex_termination_state,\n            );\n\n            // Set the termination flag\n            *termination_flag = 1;\n        }\n\n        // Call the provided function\n        let res = $func;\n\n        // Check the termination flag and handle timeout\n        unsafe {\n            if core::intrinsics::unlikely(*termination_flag == 2) {\n                crate::panic::__rex_handle_timeout();\n            } else {\n                // Reset the termination flag upon exiting\n                *termination_flag = 0;\n            }\n        }\n\n        // Return the result of the function call\n        res\n    }};\n}\n\npub(crate) fn bpf_get_smp_processor_id() -> i32 {\n    unsafe { this_cpu_read(&raw const ffi::cpu_number) }\n}\n\npub(crate) fn bpf_map_lookup_elem<'a, const MT: bpf_map_type, K, V>(\n    map: &'static RexMapHandle<MT, K, V>,\n    key: &'a K,\n) -> Option<&'a mut V>\nwhere\n    V: Copy + NoRef,\n{\n    let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) };\n    if unlikely(map_kptr.is_null()) {\n        return None;\n    }\n\n    let value = termination_check!(unsafe {\n        ffi::bpf_map_lookup_elem(map_kptr, key as *const K as *const ())\n            as *mut V\n    });\n\n    if value.is_null() {\n        None\n    } else {\n        Some(unsafe { &mut *value })\n    }\n}\n\npub(crate) fn bpf_map_update_elem<const MT: bpf_map_type, K, V>(\n    map: &'static RexMapHandle<MT, K, V>,\n    key: &K,\n    value: &V,\n    flags: u64,\n) -> Result\nwhere\n    V: Copy + NoRef,\n{\n    let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) };\n    if unlikely(map_kptr.is_null()) {\n        return Err(EINVAL as i32);\n    }\n\n    termination_check!(unsafe {\n        to_result!(ffi::bpf_map_update_elem(\n            map_kptr,\n            key as *const K as *const (),\n            value as *const V as *const (),\n            flags\n        ) as i32)\n    })\n}\n\npub(crate) fn bpf_map_delete_elem<const MT: bpf_map_type, K, V>(\n    map: &'static RexMapHandle<MT, K, V>,\n    key: &K,\n) -> Result\nwhere\n    V: Copy + NoRef,\n{\n    let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) };\n    if unlikely(map_kptr.is_null()) {\n        return Err(EINVAL as i32);\n    }\n\n    termination_check!(unsafe {\n        to_result!(ffi::bpf_map_delete_elem(\n            map_kptr,\n            key as *const K as *const ()\n        ) as i32)\n    })\n}\n\npub(crate) fn bpf_map_push_elem<const MT: bpf_map_type, K, V>(\n    map: &'static RexMapHandle<MT, K, V>,\n    value: &V,\n    flags: u64,\n) -> Result\nwhere\n    V: Copy + NoRef,\n{\n    let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) };\n    if unlikely(map_kptr.is_null()) {\n        return Err(EINVAL as i32);\n    }\n\n    termination_check!(unsafe {\n        to_result!(ffi::bpf_map_push_elem(\n            map_kptr,\n            value as *const V as *const (),\n            flags\n        ) as i32)\n    })\n}\n\npub(crate) fn bpf_map_pop_elem<const MT: bpf_map_type, K, V>(\n    map: &'static RexMapHandle<MT, K, V>,\n) -> Option<V>\nwhere\n    V: Copy + NoRef,\n{\n    let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) };\n    if unlikely(map_kptr.is_null()) {\n        return None;\n    }\n\n    let mut value: MaybeUninit<V> = MaybeUninit::uninit();\n\n    let res = termination_check!(unsafe {\n        to_result!(ffi::bpf_map_pop_elem(\n            map_kptr,\n            value.as_mut_ptr() as *mut ()\n        ) as i32)\n    });\n    res.map(|_| unsafe { value.assume_init() }).ok()\n}\n\npub(crate) fn bpf_map_peek_elem<const MT: bpf_map_type, K, V>(\n    map: &'static RexMapHandle<MT, K, V>,\n) -> Option<V>\nwhere\n    V: Copy + NoRef,\n{\n    let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) };\n    if unlikely(map_kptr.is_null()) {\n        return None;\n    }\n\n    let mut value: MaybeUninit<V> = MaybeUninit::uninit();\n\n    let res = termination_check!(unsafe {\n        to_result!(ffi::bpf_map_peek_elem(\n            map_kptr,\n            value.as_mut_ptr() as *mut ()\n        ) as i32)\n    });\n\n    res.map(|_| unsafe { value.assume_init() }).ok()\n}\n\n// pub(crate) fn bpf_for_each_map_elem<const MT: bpf_map_type, K, V, C>(\n//     map: &'static RexMapHandle<MT, K, V>,\n//     callback_fn: extern \"C\" fn(*const (), *const K, *const V, *const C) ->\n// i64,     callback_ctx: &C,\n//     flags: u64,\n// ) -> Result {\n//     let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) };\n//     if unlikely(map_kptr.is_null()) {\n//         return Err(EINVAL as i32);\n//     }\n\n//     unsafe {\n//         to_result!(ffi::bpf_for_each_map_elem(map_kptr, callback_fn as\n// *const (), callback_ctx as *const C as *const (), flags) as i32)     }\n// }\n\n// Design decision: Make the destination a generic type so that probe read\n// kernel can directly fill in variables of certain type. This also achieves\n// size checking, since T is known at compile time for monomorphization\npub(crate) fn bpf_probe_read_kernel<T>(\n    dst: &mut T,\n    unsafe_ptr: *const (),\n) -> Result\nwhere\n    T: Copy + NoRef,\n{\n    termination_check!(unsafe {\n        to_result!(ffi::bpf_probe_read_kernel(\n            dst as *mut T as *mut (),\n            core::mem::size_of::<T>() as u32,\n            unsafe_ptr,\n        ))\n    })\n}\n\npub(crate) fn bpf_jiffies64() -> u64 {\n    unsafe { core::ptr::read_volatile(&ffi::jiffies) }\n}\n\n/// Assumes `CONFIG_USE_PERCPU_NUMA_NODE_ID`\npub(crate) fn bpf_get_numa_node_id() -> i32 {\n    unsafe { this_cpu_read(&raw const ffi::numa_node) }\n}\n\n// This two functions call the original helper directly, so that confirm the\n// return value is correct\n/*\npub(crate) fn bpf_ktime_get_ns_origin() -> u64 {\n    unsafe { ffi::ktime_get_mono_fast_ns() }\n}\n\npub(crate) fn bpf_ktime_get_boot_ns_origin() -> u64 {\n    unsafe { ffi::ktime_get_boot_fast_ns() }\n}\n*/\n\npub(crate) fn bpf_ktime_get_ns() -> u64 {\n    termination_check!(unsafe { ffi::bpf_ktime_get_ns() })\n}\n\npub(crate) fn bpf_ktime_get_boot_ns() -> u64 {\n    termination_check!(unsafe { ffi::bpf_ktime_get_boot_ns() })\n}\n\npub(crate) fn bpf_ktime_get_coarse_ns() -> u64 {\n    termination_check!(unsafe { ffi::bpf_ktime_get_coarse_ns() })\n}\n\n/*\npub(crate) fn bpf_ktime_get_ns() -> u64 {\n    ktime_get_mono_fast_ns()\n}\n\npub(crate) fn bpf_ktime_get_boot_ns() -> u64 {\n    ktime_get_boot_fast_ns()\n}\n\npub(crate) fn bpf_ktime_get_coarse_ns() -> u64 {\n    ktime_get_coarse() as u64\n}\n*/\n\npub(crate) fn bpf_get_prandom_u32() -> u32 {\n    termination_check!(bpf_user_rnd_u32())\n}\n\n// In document it says that data is a pointer to an array of 64-bit values.\npub(crate) fn bpf_snprintf<const N: usize, const M: usize>(\n    str: &mut [u8; N],\n    fmt: &str,\n    data: &[u64; M],\n) -> Result {\n    termination_check!(unsafe {\n        to_result!(ffi::bpf_snprintf(\n            str.as_mut_ptr(),\n            N as u32,\n            fmt.as_ptr(),\n            data.as_ptr(),\n            M as u32,\n        ) as i32)\n    })\n}\n\nmacro_rules! base_helper_defs {\n    () => {\n        #[inline(always)]\n        pub fn bpf_get_smp_processor_id(&self) -> i32 {\n            crate::base_helper::bpf_get_smp_processor_id()\n        }\n\n        // Self should already have impl<'a>\n        #[inline(always)]\n        pub fn bpf_map_lookup_elem<'b, const MT: bpf_map_type, K, V>(\n            &self,\n            map: &'static crate::map::RexMapHandle<MT, K, V>,\n            key: &'b K,\n        ) -> Option<&'b mut V>\n        where\n            V: Copy + crate::utils::NoRef,\n        {\n            crate::base_helper::bpf_map_lookup_elem(map, key)\n        }\n\n        #[inline(always)]\n        pub fn bpf_map_update_elem<const MT: bpf_map_type, K, V>(\n            &self,\n            map: &'static crate::map::RexMapHandle<MT, K, V>,\n            key: &K,\n            value: &V,\n            flags: u64,\n        ) -> crate::Result\n        where\n            V: Copy + crate::utils::NoRef,\n        {\n            crate::base_helper::bpf_map_update_elem(map, key, value, flags)\n        }\n\n        #[inline(always)]\n        pub fn bpf_map_delete_elem<const MT: bpf_map_type, K, V>(\n            &self,\n            map: &'static crate::map::RexMapHandle<MT, K, V>,\n            key: &K,\n        ) -> crate::Result\n        where\n            V: Copy + crate::utils::NoRef,\n        {\n            crate::base_helper::bpf_map_delete_elem(map, key)\n        }\n\n        #[inline(always)]\n        pub fn bpf_map_push_elem<const MT: bpf_map_type, K, V>(\n            &self,\n            map: &'static crate::map::RexMapHandle<MT, K, V>,\n            value: &V,\n            flags: u64,\n        ) -> crate::Result\n        where\n            V: Copy + crate::utils::NoRef,\n        {\n            crate::base_helper::bpf_map_push_elem(map, value, flags)\n        }\n\n        #[inline(always)]\n        pub fn bpf_map_pop_elem<const MT: bpf_map_type, K, V>(\n            &self,\n            map: &'static crate::map::RexMapHandle<MT, K, V>,\n        ) -> Option<V>\n        where\n            V: Copy + crate::utils::NoRef,\n        {\n            crate::base_helper::bpf_map_pop_elem(map)\n        }\n\n        #[inline(always)]\n        pub fn bpf_map_peek_elem<const MT: bpf_map_type, K, V>(\n            &self,\n            map: &'static crate::map::RexMapHandle<MT, K, V>,\n        ) -> Option<V>\n        where\n            V: Copy + crate::utils::NoRef,\n        {\n            crate::base_helper::bpf_map_peek_elem(map)\n        }\n\n        #[inline(always)]\n        pub fn bpf_probe_read_kernel<T>(\n            &self,\n            dst: &mut T,\n            unsafe_ptr: *const (),\n        ) -> crate::Result\n        where\n            T: Copy + crate::utils::NoRef,\n        {\n            crate::base_helper::bpf_probe_read_kernel(dst, unsafe_ptr)\n        }\n\n        #[inline(always)]\n        pub fn bpf_jiffies64(&self) -> u64 {\n            crate::base_helper::bpf_jiffies64()\n        }\n\n        #[inline(always)]\n        pub fn bpf_get_numa_node_id(&self) -> i32 {\n            crate::base_helper::bpf_get_numa_node_id()\n        }\n\n        /*\n        #[inline(always)]\n        pub fn bpf_ktime_get_ns_origin(&self) -> u64 {\n            crate::base_helper::bpf_ktime_get_ns_origin()\n        }\n\n        #[inline(always)]\n        pub fn bpf_ktime_get_boot_ns_origin(&self) -> u64 {\n            crate::base_helper::bpf_ktime_get_boot_ns_origin()\n        }\n        */\n\n        #[inline(always)]\n        pub fn bpf_ktime_get_ns(&self) -> u64 {\n            crate::base_helper::bpf_ktime_get_ns()\n        }\n\n        #[inline(always)]\n        pub fn bpf_ktime_get_boot_ns(&self) -> u64 {\n            crate::base_helper::bpf_ktime_get_boot_ns()\n        }\n\n        #[inline(always)]\n        pub fn bpf_ktime_get_coarse_ns(&self) -> u64 {\n            crate::base_helper::bpf_ktime_get_coarse_ns()\n        }\n\n        #[inline(always)]\n        pub fn bpf_get_prandom_u32(&self) -> u32 {\n            crate::base_helper::bpf_get_prandom_u32()\n        }\n\n        #[inline(always)]\n        pub fn bpf_snprintf<const N: usize, const M: usize>(\n            &self,\n            buf: &mut [u8; N],\n            fmt: &str,\n            data: &[u64; M],\n        ) -> crate::Result {\n            crate::base_helper::bpf_snprintf(buf, fmt, data)\n        }\n\n        // #[inline(always)]\n        // pub fn bpf_ringbuf_reserve<T>(\n        //     &self,\n        //     map: &'static RexRingBuf,\n        //     size: u64,\n        //     flags: u64,\n        // ) -> *mut T {\n        //     crate::base_helper::bpf_ringbuf_reserve(map, flags)\n        // }\n        //\n        // #[inline(always)]\n        // pub fn bpf_ringbuf_submit<T>(&self, data: &mut T, flags: u64) {\n        //     crate::base_helper::bpf_ringbuf_submit(data, flags)\n        // }\n    };\n}\n\npub(crate) use base_helper_defs;\npub(crate) use termination_check;\n"
  },
  {
    "path": "rex/src/bindings/linux/kernel.rs",
    "content": "include!(concat!(env!(\"OUT_DIR\"), \"/linux/kernel.rs\"));\n"
  },
  {
    "path": "rex/src/bindings/linux/mod.rs",
    "content": "pub mod kernel;\n"
  },
  {
    "path": "rex/src/bindings/mod.rs",
    "content": "#![allow(\n    non_camel_case_types,\n    non_snake_case,\n    non_upper_case_globals,\n    unused,\n    unnecessary_transmutes\n)]\n\npub(crate) mod linux;\npub mod uapi;\n"
  },
  {
    "path": "rex/src/bindings/uapi/linux/bpf.rs",
    "content": "include!(concat!(env!(\"OUT_DIR\"), \"/uapi/linux/bpf.rs\"));\n"
  },
  {
    "path": "rex/src/bindings/uapi/linux/errno.rs",
    "content": "include!(concat!(env!(\"OUT_DIR\"), \"/uapi/linux/errno.rs\"));\n"
  },
  {
    "path": "rex/src/bindings/uapi/linux/in.rs",
    "content": "include!(concat!(env!(\"OUT_DIR\"), \"/uapi/linux/in.rs\"));\n"
  },
  {
    "path": "rex/src/bindings/uapi/linux/mod.rs",
    "content": "pub mod bpf;\npub mod errno;\npub mod r#in;\npub mod perf_event;\npub mod pkt_cls;\npub mod ptrace;\npub mod seccomp;\npub mod unistd;\n"
  },
  {
    "path": "rex/src/bindings/uapi/linux/perf_event.rs",
    "content": "include!(concat!(env!(\"OUT_DIR\"), \"/uapi/linux/perf_event.rs\"));\n"
  },
  {
    "path": "rex/src/bindings/uapi/linux/pkt_cls.rs",
    "content": "include!(concat!(env!(\"OUT_DIR\"), \"/uapi/linux/pkt_cls.rs\"));\n"
  },
  {
    "path": "rex/src/bindings/uapi/linux/ptrace.rs",
    "content": "include!(concat!(env!(\"OUT_DIR\"), \"/uapi/linux/ptrace.rs\"));\n"
  },
  {
    "path": "rex/src/bindings/uapi/linux/seccomp.rs",
    "content": "include!(concat!(env!(\"OUT_DIR\"), \"/uapi/linux/seccomp.rs\"));\n"
  },
  {
    "path": "rex/src/bindings/uapi/linux/unistd.rs",
    "content": "include!(concat!(env!(\"OUT_DIR\"), \"/uapi/linux/unistd.rs\"));\n"
  },
  {
    "path": "rex/src/bindings/uapi/mod.rs",
    "content": "pub mod linux;\n"
  },
  {
    "path": "rex/src/debug.rs",
    "content": "use core::ffi::{c_int, c_uchar};\n\nuse crate::ffi;\n\n// WARN must add \"\\0\" at the end of &str, c_str is different from rust str\n#[unsafe(no_mangle)]\npub(crate) unsafe extern \"C\" fn printk(fmt: &str, mut ap: ...) -> c_int {\n    unsafe { ffi::vprintk(fmt.as_ptr() as *const c_uchar, ap) }\n}\n"
  },
  {
    "path": "rex/src/ffi.rs",
    "content": "// All kernel symbols we need should be declared here\n\n#![allow(dead_code)]\n\nuse core::ffi::{c_uchar, VaList};\n\nuse crate::bindings::linux::kernel::{\n    bpf_perf_event_data_kern, sk_buff, task_struct, xdp_buff, MAX_BPRINTF_BUF,\n};\nuse crate::bindings::uapi::linux::bpf::{bpf_perf_event_value, bpf_spin_lock};\nuse crate::panic::{CleanupEntry, ENTRIES_SIZE};\n\n// Functions\nunsafe extern \"C\" {\n    /// `void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)`\n    ///\n    /// `struct bpf_map` is opaque in our case so make it a `*mut ()`\n    pub(crate) fn bpf_map_lookup_elem(map: *mut (), key: *const ()) -> *mut ();\n\n    /// `long bpf_map_update_elem(struct bpf_map *map, const void *key, const\n    /// void *value, u64 flags)`\n    ///\n    /// `struct bpf_map` is opaque in our case so make it a `*mut ()`\n    pub(crate) fn bpf_map_update_elem(\n        map: *mut (),\n        key: *const (),\n        value: *const (),\n        flags: u64,\n    ) -> i64;\n\n    /// `long bpf_map_delete_elem(struct bpf_map *map, const void *key)`\n    ///\n    /// `struct bpf_map` is opaque in our case so make it a `*mut ()`\n    pub(crate) fn bpf_map_delete_elem(map: *mut (), key: *const ()) -> i64;\n\n    /// `long bpf_map_push_elem(struct bpf_map *map, const void *value, u64\n    /// flags)`\n    ///\n    /// `struct bpf_map` is opaque in our case so make it a `*mut ()`\n    pub(crate) fn bpf_map_push_elem(\n        map: *mut (),\n        value: *const (),\n        flags: u64,\n    ) -> i64;\n\n    /// `long bpf_map_pop_elem(struct bpf_map *map, void *value)`\n    ///\n    /// `struct bpf_map` is opaque in our case so make it a `*mut ()`\n    pub(crate) fn bpf_map_pop_elem(map: *mut (), value: *const ()) -> i64;\n\n    /// `long bpf_map_peek_elem(struct bpf_map *map, void *value)`\n    ///\n    /// `struct bpf_map` is opaque in our case so make it a `*mut ()`\n    pub(crate) fn bpf_map_peek_elem(map: *mut (), value: *const ()) -> i64;\n\n    /// `long bpf_probe_read_kernel(void *dst, u32 size, const void\n    /// *unsafe_ptr)`\n    pub(crate) fn bpf_probe_read_kernel(\n        dst: *mut (),\n        size: u32,\n        unsafe_ptr: *const (),\n    ) -> i64;\n\n    /// `u64 notrace ktime_get_mono_fast_ns(void)`\n    pub(crate) fn ktime_get_mono_fast_ns() -> u64;\n\n    /// `u64 notrace ktime_get_boot_fast_ns(void)`\n    pub(crate) fn ktime_get_boot_fast_ns() -> u64;\n\n    /// `u64 bpf_ktime_get_ns(void)`\n    pub(crate) fn bpf_ktime_get_ns() -> u64;\n\n    /// `u64 bpf_ktime_get_boot_ns(void)`\n    pub(crate) fn bpf_ktime_get_boot_ns() -> u64;\n\n    /// `u64 bpf_ktime_get_coarse_ns(void)`\n    pub(crate) fn bpf_ktime_get_coarse_ns() -> u64;\n\n    /// `u32 get_random_u32(void)`\n    pub(crate) fn get_random_u32() -> u32;\n\n    /// `long bpf_snprintf_btf(char *str, u32 str_size, struct btf_ptr *ptr, u32\n    /// btf_ptr_size, u64 flags)`\n    pub(crate) fn bpf_snprintf(\n        str: *mut u8,\n        str_size: u32,\n        fmt: *const u8,\n        data: *const u64,\n        data_len: u32,\n    ) -> i64;\n\n    /// `asmlinkage int vprintk(const char *fmt, va_list args)`\n    pub(crate) fn vprintk(fmt: *const c_uchar, args: VaList) -> i32;\n\n    /// `__nocfi noinline void notrace __noreturn rex_landingpad(char *msg)`\n    ///\n    /// The in-kernel panic landingpad for panic recovery\n    pub(crate) fn rex_landingpad() -> !;\n\n    /// `long bpf_spin_lock(struct bpf_spin_lock *lock)`\n    pub(crate) fn bpf_spin_lock(lock: *mut bpf_spin_lock) -> i64;\n\n    /// `long bpf_spin_unlock(struct bpf_spin_lock *lock)`\n    pub(crate) fn bpf_spin_unlock(lock: *mut bpf_spin_lock) -> i64;\n\n    /// `asmlinkage void just_return_func(void)`\n    pub(crate) fn just_return_func();\n\n    /// `long bpf_get_stackid_pe(struct bpf_perf_event_data_kern *ctx, struct\n    /// bpf_map *map, u64 flags)`\n    ///\n    /// The specialized version of `bpf_get_stackid` for perf event programs\n    ///\n    /// Also allow improper_ctypes here since the empty lock_class_key is\n    /// guaranteed not touched by us\n    #[allow(improper_ctypes)]\n    pub(crate) fn bpf_get_stackid_pe(\n        ctx: *const bpf_perf_event_data_kern,\n        map: *mut (),\n        flags: u64,\n    ) -> i64;\n\n    /// `long bpf_perf_prog_read_value(struct bpf_perf_event_data *ctx, struct\n    /// bpf_perf_event_value *buf, u32 buf_size)`\n    ///\n    /// Also allow improper_ctypes here since the empty lock_class_key is\n    /// guaranteed not touched by us\n    #[allow(improper_ctypes)]\n    pub(crate) fn bpf_perf_prog_read_value(\n        ctx: *const bpf_perf_event_data_kern,\n        buf: &mut bpf_perf_event_value,\n        size: u32,\n    ) -> i64;\n\n    /// `long bpf_perf_event_output_tp(void *tp_buff, struct bpf_map *map, u64\n    /// flags, void *data, u64 size)`\n    pub(crate) fn bpf_perf_event_output_tp(\n        tp_buff: *const (),\n        map: *mut (),\n        flags: u64,\n        data: *const (),\n        size: u64,\n    ) -> i64;\n\n    /// `long bpf_perf_event_read_value(struct bpf_map *map, u64 flags,\n    /// struct bpf_perf_event_value *buf, u32 buf_size)`\n    /// same reason for use of improper_ctypes as bpf_perf_prog_read_value\n    #[allow(improper_ctypes)]\n    pub(crate) fn bpf_perf_event_read_value(\n        map: *mut (),\n        flags: u64,\n        buf: &mut bpf_perf_event_value,\n        buf_size: u32,\n    ) -> i64;\n\n    /// `long bpf_skb_event_output(struct sk_buff *skb, struct bpf_map *map, u64\n    /// flags, void *meta, u64 meta_size)`\n    /// The compiler complains about some non-FFI safe type, but since the\n    /// kernel is using it fine it should be safe for an FFI call using C ABI\n    #[allow(improper_ctypes)]\n    pub(crate) fn bpf_skb_event_output(\n        skb: *const sk_buff,\n        map: *mut (),\n        flags: u64,\n        meta: *const (),\n        meta_size: u64,\n    ) -> i64;\n\n    /// `long bpf_xdp_event_output(struct xdp_buff *xdp, struct bpf_map *map,\n    /// u64 flags, void *meta, u64 meta_size)`\n    /// The compiler complains about some non-FFI safe type, but since the\n    /// kernel is using it fine it should be safe for an FFI call using C ABI\n    #[allow(improper_ctypes)]\n    pub(crate) fn bpf_xdp_event_output(\n        xdp: *const xdp_buff,\n        map: *mut (),\n        flags: u64,\n        meta: *const (),\n        meta_size: u64,\n    ) -> i64;\n\n    /// `long bpf_xdp_adjust_head(struct xdp_buff *xdp, int offset)`\n    ///\n    /// The compiler complains about some non-FFI safe type, but since the\n    /// kernel is using it fine it should be safe for an FFI call using C ABI\n    #[allow(improper_ctypes)]\n    pub(crate) fn bpf_xdp_adjust_head(xdp: *mut xdp_buff, offset: i32) -> i32;\n\n    /// long bpf_xdp_adjust_tail(struct xdp_buff *xdp, int offset)\n    ///\n    /// The compiler complains about some non-FFI safe type, but since the\n    /// kernel is using it fine it should be safe for an FFI call using C ABI\n    #[allow(improper_ctypes)]\n    pub(crate) fn bpf_xdp_adjust_tail(xdp: *mut xdp_buff, offset: i32) -> i32;\n\n    /// long bpf_clone_redirect(struct sk_buff *skb, u32 ifindex, u64 flags)\n    ///\n    /// The compiler complains about some non-FFI safe type, but since the\n    /// kernel is using it fine it should be safe for an FFI call using C ABI\n    #[allow(improper_ctypes)]\n    pub(crate) fn bpf_clone_redirect(\n        skb: *mut sk_buff,\n        ifindex: u32,\n        flags: u64,\n    ) -> i32;\n\n    /// void *bpf_ringbuf_reserve(void *ringbuf, u64 size, u64 flags)\n    pub(crate) fn bpf_ringbuf_reserve(\n        ringbuf: *mut (),\n        size: u64,\n        flags: u64,\n    ) -> *mut ();\n\n    /// long bpf_ringbuf_output(void *ringbuf, void *data, u64 size, u64 flags)\n    // data is marked `ARG_PTR_TO_MEM | MEM_RDONLY`, which implies the argument\n    // is comptiable with readonly memory and does not modifiy the memory\n    // pointed by the pointer, therefore, we use a *const () type.\n    pub(crate) fn bpf_ringbuf_output(\n        ringbuf: *mut (),\n        data: *const (),\n        size: u64,\n        flags: u64,\n    ) -> i64;\n\n    /// void bpf_ringbuf_submit(void *data, u64 flags)\n    pub(crate) fn bpf_ringbuf_submit(data: *mut (), flags: u64);\n\n    /// void bpf_ringbuf_discard(void *data, u64 flags)\n    pub(crate) fn bpf_ringbuf_discard(data: *mut (), flags: u64);\n\n    /// u64 bpf_ringbuf_query(void *ringbuf, u64 flags)\n    pub(crate) fn bpf_ringbuf_query(ringbuf: *mut (), flags: u64) -> u64;\n\n    /// void rex_trace_printk(void)\n    pub(crate) fn rex_trace_printk();\n\n    /// __bpf_kfunc struct task_struct *bpf_task_from_pid(s32 pid)\n    pub(crate) fn bpf_task_from_pid(pid: i32) -> *mut task_struct;\n\n    /// __bpf_kfunc void bpf_task_release(struct task_struct *p)\n    pub(crate) fn bpf_task_release(task: *mut task_struct);\n}\n\n// Global variables\nunsafe extern \"C\" {\n    /// `extern unsigned long volatile __cacheline_aligned_in_smp\n    /// __jiffy_arch_data jiffies;`\n    ///\n    /// Real definition done via linker script (`arch/x86/kernel/vmlinux.lds.S`)\n    /// and is made an alias to `jiffies_64` on x86\n    pub(crate) static jiffies: u64;\n\n    /// `DEFINE_PER_CPU(int, numa_node);`\n    pub(crate) static numa_node: i32;\n\n    /// `DEFINE_PER_CPU(struct rex_cleanup_entry[64], rex_cleanup_entries)\n    /// ____cacheline_aligned = { 0 };`\n    ///\n    /// Used for cleanup upon panic\n    ///\n    /// Pointee type omitted since this per-cpu variable will never be directly\n    /// dereferenced, it is always used for per-cpu address calculation\n    ///\n    /// Allow the use of rust fn ptr as the function is only called in Rust\n    #[allow(improper_ctypes)]\n    pub(crate) static mut rex_cleanup_entries: [CleanupEntry; ENTRIES_SIZE];\n\n    /// `DEFINE_PER_CPU(void *, rex_stack_ptr);`\n    ///\n    /// Top of the per-cpu stack for rex programs\n    pub(crate) static rex_stack_ptr: u64;\n\n    /// `DECLARE_PER_CPU_CACHE_HOT(struct task_struct *, current_task);`\n    ///\n    /// Per-cpu pointer of the current task\n    // rustc properly treats the empty `lock_class_key` as zero-sized\n    #[allow(improper_ctypes)]\n    pub(crate) static current_task: *mut task_struct;\n\n    /// `DECLARE_PER_CPU_CACHE_HOT(int, cpu_number);`\n    ///\n    /// Current CPU number\n    pub(crate) static cpu_number: i32;\n\n    ///  `DEFINE_PER_CPU(int, rex_termination_state);`\n    ///  \n    ///  Used to indidicate whether a BPF program in a CPU is executing\n    ///  inside a helper, or inside a panic handler, or just in BPF text.\n    pub(crate) static mut rex_termination_state: u8;\n\n    /// DEFINE_PER_CPU_READ_MOSTLY(unsigned long, this_cpu_off) =\n    /// BOOT_PERCPU_OFFSET;\n    ///\n    /// Offset on the current\n    pub(crate) static this_cpu_off: u64;\n\n    /// DEFINE_PER_CPU(char[MAX_BPRINTF_BUF], rex_log_buf) = { 0 };\n    pub(crate) static mut rex_log_buf: [u8; MAX_BPRINTF_BUF as usize];\n}\n"
  },
  {
    "path": "rex/src/kprobe/kprobe_impl.rs",
    "content": "use core::marker::PhantomData;\n\nuse crate::bindings::uapi::linux::bpf::bpf_map_type;\nuse crate::ffi;\nuse crate::pt_regs::PtRegs;\nuse crate::task_struct::TaskStruct;\n\n#[repr(C)]\npub struct kprobe {\n    _placeholder: PhantomData<()>,\n}\n\nimpl kprobe {\n    crate::base_helper::base_helper_defs!();\n\n    pub const unsafe fn new() -> kprobe {\n        Self {\n            _placeholder: PhantomData,\n        }\n    }\n\n    // Now returns a mutable ref, but since every reg is private the user prog\n    // cannot change reg contents. The user should not be able to directly\n    // assign this reference a new value either, given that they will not able\n    // to create another instance of pt_regs (private fields, no pub ctor)\n    pub unsafe fn convert_ctx(&self, ctx: *mut ()) -> &'static mut PtRegs {\n        // ctx has actual type *mut crate::bindings::linux::kernel::pt_regs\n        // therefore it is safe to just interpret it as a *mut pt_regs\n        // since the later is #[repr(transparent)] over the former\n        unsafe { &mut *(ctx as *mut PtRegs) }\n    }\n\n    #[cfg(CONFIG_BPF_KPROBE_OVERRIDE = \"y\")]\n    pub fn bpf_override_return(&self, regs: &mut PtRegs, rc: u64) -> i32 {\n        regs.regs.ax = rc;\n        regs.regs.ip = ffi::just_return_func as *const () as u64;\n        0\n    }\n\n    pub fn bpf_get_current_task(&self) -> Option<TaskStruct> {\n        TaskStruct::get_current_task()\n    }\n}\n"
  },
  {
    "path": "rex/src/kprobe/mod.rs",
    "content": "mod kprobe_impl;\n\npub use kprobe_impl::*;\n"
  },
  {
    "path": "rex/src/lib.rs",
    "content": "#![no_std]\n#![feature(\n    array_ptr_get,\n    auto_traits,\n    c_variadic,\n    core_intrinsics,\n    negative_impls\n)]\n#![allow(non_camel_case_types, internal_features)]\n\npub mod kprobe;\npub mod map;\npub mod perf_event;\npub mod pt_regs;\npub mod sched_cls;\npub mod spinlock;\npub mod task_struct;\npub mod tracepoint;\npub mod utils;\npub mod xdp;\n\nmod base_helper;\nmod bindings;\nmod debug;\nmod ffi;\nmod log;\nmod panic;\nmod per_cpu;\nmod random32;\n\nextern crate paste;\n\npub use rex_macros::*;\n\n#[cfg(not(CONFIG_KALLSYMS_ALL = \"y\"))]\ncompile_error!(\"CONFIG_KALLSYMS_ALL is required for rex\");\n\npub use bindings::uapi::*;\npub use log::rex_trace_printk;\npub use utils::Result;\n"
  },
  {
    "path": "rex/src/log.rs",
    "content": "use core::fmt::{self, Write};\n\nuse crate::base_helper::termination_check;\nuse crate::bindings::uapi::linux::errno::E2BIG;\nuse crate::ffi;\nuse crate::per_cpu::this_cpu_ptr_mut;\n\n/// An abstraction over the in-kernel per-cpu log buffer\n/// This struct implements [`Write`], and therefore can be used for formatting\npub(crate) struct LogBuf {\n    buf: &'static mut [u8],\n    off: usize,\n}\n\nimpl LogBuf {\n    /// Construct a new `LogBuf` from the kernel log buffer on the current CPU\n    pub(crate) fn new() -> Self {\n        let buf = unsafe {\n            &mut *this_cpu_ptr_mut(&raw mut ffi::rex_log_buf).as_mut_slice()\n        };\n        Self { buf, off: 0 }\n    }\n\n    /// Reset the offset of the buffer, i.e. discarding all contents not yet\n    /// sent to the kernel\n    #[inline(always)]\n    pub(crate) fn reset(&mut self) {\n        self.off = 0;\n    }\n}\n\nimpl Write for LogBuf {\n    /// Writes a string slice into the kernel buffer on this CPU\n    fn write_str(&mut self, s: &str) -> fmt::Result {\n        let input_len = s.len();\n        let available = self.buf.len() - self.off - 1;\n\n        // Make sure we have enough space\n        if input_len > available {\n            return Err(fmt::Error);\n        }\n\n        // Copy and null-terminated the buf\n        let end = self.off + input_len;\n        self.buf[self.off..end].copy_from_slice(s.as_bytes());\n        self.buf[end] = 0;\n\n        // Update the write offset\n        self.off = end;\n\n        Ok(())\n    }\n}\n\n#[macro_export]\nmacro_rules! function_name {\n    () => {{\n        fn f() {}\n        fn type_name_of<T>(_: T) -> &'static str {\n            core::any::type_name::<T>()\n        }\n        let data = type_name_of(f);\n        &data[..data.len() - 3]\n    }};\n}\n\n/// Prints a message defined by `args` to the TraceFS file\n/// `/sys/kernel/debug/tracing/trace`.\npub fn rex_trace_printk(args: fmt::Arguments<'_>) -> crate::Result {\n    // Format and write message to the per-cpu buf, then print it out\n    write!(&mut LogBuf::new(), \"{}\", args).map_err(|_| -(E2BIG as i32))?;\n    termination_check!(unsafe { ffi::rex_trace_printk() });\n\n    Ok(0)\n}\n\n/// `println`-style convenience macro for [`rex_trace_printk`].\n/// Different from `println`, this macro produces the value of [`crate::Result`]\n/// from [`rex_trace_printk`]\n#[cfg(feature = \"debug_printk\")]\n#[macro_export]\nmacro_rules! rex_printk {\n    ($($arg:tt)*) => {{\n        $crate::rex_trace_printk(\n            format_args!(\n                \"[{}] {}\",\n                $crate::function_name!(),\n                format_args!($($arg)*)\n            ),\n        )\n    }};\n}\n\n#[cfg(not(feature = \"debug_printk\"))]\n#[macro_export]\nmacro_rules! rex_printk {\n    ($($arg:tt)*) => {\n        $crate::Result::Ok(0)\n    };\n}\n"
  },
  {
    "path": "rex/src/map.rs",
    "content": "use core::fmt::{self, Write};\nuse core::intrinsics::unlikely;\nuse core::marker::PhantomData;\nuse core::ops::{Deref, DerefMut};\nuse core::{mem, ptr, slice};\n\nuse crate::base_helper::{\n    bpf_map_delete_elem, bpf_map_lookup_elem, bpf_map_peek_elem,\n    bpf_map_pop_elem, bpf_map_push_elem, bpf_map_update_elem,\n    termination_check,\n};\nuse crate::ffi;\nuse crate::linux::bpf::{\n    bpf_map_type, BPF_ANY, BPF_EXIST, BPF_MAP_TYPE_ARRAY, BPF_MAP_TYPE_HASH,\n    BPF_MAP_TYPE_PERCPU_ARRAY, BPF_MAP_TYPE_PERF_EVENT_ARRAY,\n    BPF_MAP_TYPE_QUEUE, BPF_MAP_TYPE_RINGBUF, BPF_MAP_TYPE_STACK,\n    BPF_MAP_TYPE_STACK_TRACE, BPF_NOEXIST, BPF_RB_AVAIL_DATA, BPF_RB_CONS_POS,\n    BPF_RB_PROD_POS, BPF_RB_RING_SIZE,\n};\nuse crate::linux::errno::EINVAL;\nuse crate::utils::{\n    to_result, NoRef, PerfEventMaskedCPU, PerfEventStreamer, Result,\n};\n\n/// Rex equivalent to be used for map APIs in place of the `struct bpf_map`.\n/// The key and the value type are encoded as generics types `K` and `V`.\n/// The map type is encoded as a const-generic using the `bpf_map_type` enum.\n#[repr(C)]\npub struct RexMapHandle<const MT: bpf_map_type, K, V>\nwhere\n    V: Copy + NoRef,\n{\n    // Map metadata\n    map_type: u32,\n    key_size: u32,\n    val_size: u32,\n    max_size: u32,\n    map_flag: u32,\n\n    // Actual kernel side map pointer\n    pub(crate) kptr: *mut (),\n\n    // Zero-sized marker\n    key_type: PhantomData<K>,\n    val_type: PhantomData<V>,\n}\n\nimpl<const MT: bpf_map_type, K, V> RexMapHandle<MT, K, V>\nwhere\n    V: Copy + NoRef,\n{\n    pub const fn new(ms: u32, mf: u32) -> RexMapHandle<MT, K, V> {\n        Self {\n            map_type: MT,\n            key_size: mem::size_of::<K>() as u32,\n            val_size: mem::size_of::<V>() as u32,\n            max_size: ms,\n            map_flag: mf,\n            kptr: ptr::null_mut(),\n            key_type: PhantomData,\n            val_type: PhantomData,\n        }\n    }\n}\n\nunsafe impl<const MT: bpf_map_type, K, V> Sync for RexMapHandle<MT, K, V> where\n    V: Copy + NoRef\n{\n}\n\npub type RexStackTrace<K, V> = RexMapHandle<BPF_MAP_TYPE_STACK_TRACE, K, V>;\npub type RexPerCPUArrayMap<V> = RexMapHandle<BPF_MAP_TYPE_PERCPU_ARRAY, u32, V>;\npub type RexPerfEventArray<V> =\n    RexMapHandle<BPF_MAP_TYPE_PERF_EVENT_ARRAY, u32, V>;\npub type RexArrayMap<V> = RexMapHandle<BPF_MAP_TYPE_ARRAY, u32, V>;\npub type RexHashMap<K, V> = RexMapHandle<BPF_MAP_TYPE_HASH, K, V>;\npub type RexStack<V> = RexMapHandle<BPF_MAP_TYPE_STACK, (), V>;\npub type RexQueue<V> = RexMapHandle<BPF_MAP_TYPE_QUEUE, (), V>;\npub type RexRingBuf = RexMapHandle<BPF_MAP_TYPE_RINGBUF, (), ()>;\n\nimpl<'a, K, V> RexHashMap<K, V>\nwhere\n    V: Copy + NoRef,\n{\n    pub fn insert(&'static self, key: &K, value: &V) -> Result {\n        bpf_map_update_elem(self, key, value, BPF_ANY as u64)\n    }\n\n    pub fn insert_new(&'static self, key: &K, value: &V) -> Result {\n        bpf_map_update_elem(self, key, value, BPF_NOEXIST as u64)\n    }\n\n    pub fn update(&'static self, key: &K, value: &V) -> Result {\n        bpf_map_update_elem(self, key, value, BPF_EXIST as u64)\n    }\n\n    pub fn get_mut(&'static self, key: &'a K) -> Option<&'a mut V> {\n        bpf_map_lookup_elem(self, key)\n    }\n\n    pub fn delete(&'static self, key: &K) -> Result {\n        bpf_map_delete_elem(self, key)\n    }\n}\n\nimpl<'a, V> RexArrayMap<V>\nwhere\n    V: Copy + NoRef,\n{\n    pub fn insert(&'static self, key: &u32, value: &V) -> Result {\n        bpf_map_update_elem(self, key, value, BPF_ANY as u64)\n    }\n\n    pub fn get_mut(&'static self, key: &'a u32) -> Option<&'a mut V> {\n        bpf_map_lookup_elem(self, key)\n    }\n\n    pub fn delete(&'static self, key: &u32) -> Result {\n        bpf_map_delete_elem(self, key)\n    }\n}\n\nimpl<V> RexPerfEventArray<V>\nwhere\n    V: Copy + NoRef,\n{\n    pub fn output<P: PerfEventStreamer>(\n        &'static self,\n        program: &P,\n        ctx: &P::Context,\n        data: &V,\n        cpu: PerfEventMaskedCPU,\n    ) -> Result {\n        program.output_event(ctx, self, data, cpu)\n    }\n}\n\nimpl<V> RexStack<V>\nwhere\n    V: Copy + NoRef,\n{\n    pub fn push(&'static self, value: &V) -> Result {\n        bpf_map_push_elem(self, value, BPF_ANY as u64)\n    }\n\n    pub fn force_push(&'static self, value: &V) -> Result {\n        bpf_map_push_elem(self, value, BPF_EXIST as u64)\n    }\n\n    pub fn pop(&'static self) -> Option<V> {\n        bpf_map_pop_elem(self)\n    }\n\n    pub fn peek(&'static self) -> Option<V> {\n        bpf_map_peek_elem(self)\n    }\n}\n\nimpl<V> RexQueue<V>\nwhere\n    V: Copy + NoRef,\n{\n    pub fn push(&'static self, value: &V) -> Result {\n        bpf_map_push_elem(self, value, BPF_ANY as u64)\n    }\n\n    pub fn force_push(&'static self, value: &V) -> Result {\n        bpf_map_push_elem(self, value, BPF_EXIST as u64)\n    }\n\n    pub fn pop(&'static self) -> Option<V> {\n        bpf_map_pop_elem(self)\n    }\n\n    pub fn peek(&'static self) -> Option<V> {\n        bpf_map_peek_elem(self)\n    }\n}\n\nimpl RexRingBuf {\n    /// Reserves `size` bytes of payload in the ring buffer.\n    ///\n    /// If the operation succeeds, A [`RexRingBufEntry`] representing the\n    /// payload is returned, otherwise (e.g., there is not enough memory\n    /// available), `None` is returned.\n    pub fn reserve<'a>(\n        &'static self,\n        size: usize,\n    ) -> Option<RexRingBufEntry<'a>> {\n        let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) };\n        if unlikely(map_kptr.is_null()) {\n            return None;\n        }\n\n        let data = termination_check!(unsafe {\n            ffi::bpf_ringbuf_reserve(map_kptr, size as u64, 0)\n        });\n\n        if data.is_null() {\n            None\n        } else {\n            let data =\n                unsafe { slice::from_raw_parts_mut(data as *mut u8, size) };\n            Some(RexRingBufEntry { data, off: 0 })\n        }\n    }\n\n    /// Copies bytes from the `data` slice into the ring buffer.\n    ///\n    /// If [`crate::linux::bpf::BPF_RB_NO_WAKEUP`] is specified in `flags`,\n    /// no notification of new data availability is sent.\n    /// If [`crate::linux::bpf::BPF_RB_FORCE_WAKEUP`] is specified in `flags`,\n    /// notification of new data availability is sent unconditionally.\n    /// If `0` is specified in `flags`, an adaptive notification of new data\n    /// availability is sent.\n    ///\n    /// Returns a [`crate::Result`] on whether the operation is successful\n    pub fn output(&'static self, data: &[u8], flags: u64) -> crate::Result {\n        let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) };\n        if unlikely(map_kptr.is_null()) {\n            return Err(EINVAL as i32);\n        }\n\n        termination_check!(unsafe {\n            to_result!(ffi::bpf_ringbuf_output(\n                map_kptr,\n                data.as_ptr() as *const (),\n                data.len() as u64,\n                flags\n            ))\n        })\n    }\n\n    /// Queries the amount of data not yet consumed.\n    ///\n    /// Returns `None` is `self` is not a valid ring buffer.\n    pub fn available_bytes(&'static self) -> Option<u64> {\n        let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) };\n        if unlikely(map_kptr.is_null()) {\n            return None;\n        }\n\n        termination_check!(unsafe {\n            Some(ffi::bpf_ringbuf_query(map_kptr, BPF_RB_AVAIL_DATA as u64))\n        })\n    }\n\n    /// Queries the size of ring buffer.\n    ///\n    /// Returns `None` is `self` is not a valid ring buffer.\n    pub fn size(&'static self) -> Option<u64> {\n        let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) };\n        if unlikely(map_kptr.is_null()) {\n            return None;\n        }\n\n        termination_check!(unsafe {\n            Some(ffi::bpf_ringbuf_query(map_kptr, BPF_RB_RING_SIZE as u64))\n        })\n    }\n\n    /// Queries the consumer position, which may wrap around.\n    ///\n    /// Returns `None` is `self` is not a valid ring buffer.\n    pub fn consumer_position(&'static self) -> Option<u64> {\n        let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) };\n        if unlikely(map_kptr.is_null()) {\n            return None;\n        }\n\n        termination_check!(unsafe {\n            Some(ffi::bpf_ringbuf_query(map_kptr, BPF_RB_CONS_POS as u64))\n        })\n    }\n\n    /// Queries the Producer(s) position which may wrap around.\n    ///\n    /// Returns `None` is `self` is not a valid ring buffer.\n    pub fn producer_position(&'static self) -> Option<u64> {\n        let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) };\n        if unlikely(map_kptr.is_null()) {\n            return None;\n        }\n\n        termination_check!(unsafe {\n            Some(ffi::bpf_ringbuf_query(map_kptr, BPF_RB_PROD_POS as u64))\n        })\n    }\n}\n\npub struct RexRingBufEntry<'a> {\n    data: &'a mut [u8],\n    off: usize, // offset when the entry is used as a &str\n}\n\nimpl RexRingBufEntry<'_> {\n    /// Consumes the reserved payload and submits it to the ring buffer.\n    ///\n    /// If [`crate::linux::bpf::BPF_RB_NO_WAKEUP`] is specified in `flags`,\n    /// no notification of new data availability is sent.\n    /// If [`crate::linux::bpf::BPF_RB_FORCE_WAKEUP`] is specified in `flags`,\n    /// notification of new data availability is sent unconditionally.\n    /// If `0` is specified in `flags`, an adaptive notification of new data\n    /// availability is sent.\n    ///\n    /// This method always succeeds.\n    pub fn submit(self, flags: u64) {\n        termination_check!(unsafe {\n            ffi::bpf_ringbuf_submit(self.data.as_mut_ptr() as *mut (), flags)\n        });\n        // Avoid calling ringbuf_discard twice\n        mem::forget(self);\n    }\n\n    /// Consumes the reserved payload and discards it.\n    ///\n    /// If [`crate::linux::bpf::BPF_RB_NO_WAKEUP`] is specified in `flags`,\n    /// no notification of new data availability is sent.\n    /// If [`crate::linux::bpf::BPF_RB_FORCE_WAKEUP`] is specified in `flags`,\n    /// notification of new data availability is sent unconditionally.\n    /// If `0` is specified in `flags`, an adaptive notification of new data\n    /// availability is sent.\n    ///\n    /// This method always succeeds.\n    pub fn discard(self, flags: u64) {\n        termination_check!(unsafe {\n            ffi::bpf_ringbuf_discard(self.data.as_mut_ptr() as *mut (), flags)\n        });\n        // Avoid calling ringbuf_discard twice\n        mem::forget(self);\n    }\n}\n\nimpl Write for RexRingBufEntry<'_> {\n    fn write_str(&mut self, s: &str) -> fmt::Result {\n        let input_len = s.len();\n\n        // Remaining capacity plus the space reserved for the null-terminated\n        let available = self.data.len().saturating_sub(self.off + 1);\n\n        // Make sure we have enough space\n        if input_len > available {\n            return Err(fmt::Error);\n        }\n\n        // Copy and null-terminated the buf\n        let end = self.off + input_len;\n        self.data[self.off..end].copy_from_slice(s.as_bytes());\n        self.data[end] = 0;\n\n        // Update the write offset\n        self.off = end;\n\n        Ok(())\n    }\n}\n\nimpl Deref for RexRingBufEntry<'_> {\n    type Target = [u8];\n\n    fn deref(&self) -> &Self::Target {\n        self.data\n    }\n}\n\nimpl DerefMut for RexRingBufEntry<'_> {\n    fn deref_mut(&mut self) -> &mut Self::Target {\n        self.data\n    }\n}\n\nimpl core::ops::Drop for RexRingBufEntry<'_> {\n    /// Discard reserved payload when dropped\n    fn drop(&mut self) {\n        termination_check!(unsafe {\n            ffi::bpf_ringbuf_discard(self.data.as_mut_ptr() as *mut (), 0)\n        });\n    }\n}\n"
  },
  {
    "path": "rex/src/panic.rs",
    "content": "//! Implementation of various routines/frameworks related to EH/termination\n\nuse core::fmt::Write;\nuse core::panic::PanicInfo;\n\nuse crate::ffi;\nuse crate::log::LogBuf;\nuse crate::per_cpu::this_cpu_ptr_mut;\n\n/// Needs to match the kernel side per-cpu definition\npub(crate) const ENTRIES_SIZE: usize = 64;\n\npub(crate) type CleanupFn = unsafe fn(*mut ()) -> ();\n\n/// Aggregate to hold cleanup information of a specific object. The information\n/// is used during panics to ensure proper cleanup of allocated kernel\n/// resources. The `valid` field is used to mark whether this given entry holds\n/// valid information. The cleanup will happen in the form of\n/// `cleanup_fn(cleanup_arg)`\n///\n/// `#[repr(C)]` is needed because this struct is used from the kernel side.\n#[derive(Debug, Copy, Clone)]\n#[repr(C)]\npub(crate) struct CleanupEntry {\n    pub(crate) valid: u64,\n    pub(crate) cleanup_fn: Option<CleanupFn>,\n    pub(crate) cleanup_arg: *mut (),\n}\n\nimpl CleanupEntry {\n    /// Create a new entry with valid function and argument\n    #[inline]\n    pub(crate) fn new(cleanup_fn: CleanupFn, cleanup_arg: *mut ()) -> Self {\n        Self {\n            valid: 1,\n            cleanup_fn: Some(cleanup_fn),\n            cleanup_arg,\n        }\n    }\n\n    /// Run cleanup function\n    #[inline]\n    pub(crate) unsafe fn cleanup(&self) {\n        if self.valid != 0 {\n            if let Some(cleanup_fn) = self.cleanup_fn {\n                unsafe {\n                    (cleanup_fn)(self.cleanup_arg);\n                }\n            }\n        }\n    }\n}\n\nimpl Default for CleanupEntry {\n    /// Create a default entry without valid function and argument\n    #[inline]\n    fn default() -> Self {\n        Self {\n            valid: 0,\n            cleanup_fn: None,\n            cleanup_arg: core::ptr::null_mut(),\n        }\n    }\n}\n\n/// Represents an array of `CleanupEntry` on a given CPU. The backing storage\n/// is defined as a per-cpu array in the kernel.\npub(crate) struct CleanupEntries<'a> {\n    entries: &'a mut [CleanupEntry],\n}\n\nimpl<'a> CleanupEntries<'a> {\n    /// Retrieve the array of `CleanupEntry` on the current CPU.\n    #[inline]\n    fn this_cpu_cleanup_entries() -> CleanupEntries<'a> {\n        let entries: &mut [CleanupEntry];\n        unsafe {\n            entries = &mut *this_cpu_ptr_mut(&raw mut ffi::rex_cleanup_entries)\n                .as_mut_slice();\n        }\n        Self { entries }\n    }\n\n    /// Finds the next empty entry in the array\n    ///\n    /// Triggers a panic when the array is full. This is allowed because\n    /// `CleanupEntries::register_cleanup` is its only caller and is only\n    /// called by object constructors\n    #[inline]\n    fn find_next_emtpy_entry(&mut self) -> (usize, &mut CleanupEntry) {\n        for (idx, entry) in self.entries.iter_mut().enumerate() {\n            if entry.valid == 0 {\n                return (idx, entry);\n            }\n        }\n        panic!(\"Object count exceeded\\n\");\n    }\n\n    /// This function is (and must only be) called by object constructors\n    ///\n    /// Panic is allowed here\n    pub(crate) fn register_cleanup(\n        cleanup_fn: CleanupFn,\n        cleanup_arg: *mut (),\n    ) -> usize {\n        let mut entries = Self::this_cpu_cleanup_entries();\n        let (idx, entry) = entries.find_next_emtpy_entry();\n        *entry = CleanupEntry::new(cleanup_fn, cleanup_arg);\n        idx\n    }\n\n    /// This function is called by the object drop handler. It invalidates the\n    /// entry corresponding to the object.\n    pub(crate) fn deregister_cleanup(idx: usize) {\n        let entries = Self::this_cpu_cleanup_entries();\n        entries.entries[idx].valid = 0;\n    }\n\n    /// This function is called on panic to cleanup everything on the current\n    /// CPU. It **must** not cause another panic\n    pub(crate) unsafe fn cleanup_all() {\n        let entries = Self::this_cpu_cleanup_entries();\n        for entry in entries.entries.iter_mut() {\n            unsafe {\n                entry.cleanup();\n            }\n            entry.valid = 0;\n        }\n    }\n}\n\n// The best way to deal with this is probably insert it directly in LLVM IR as\n// an inline asm block\n// For now, use inline(always) to hint the compiler for inlining if LTO is on\n#[allow(unused_attributes)]\n#[unsafe(no_mangle)]\n// Note: Rust warns that inline(always) is ignored on no_mangle functions,\n// #[inline(always)] + #[no_mangle] under fat LTO generally means: inline\n// internally where possible, but still keep the exported symbol\n#[inline(always)]\nunsafe fn __rex_check_stack() {\n    // The program can only use the top 4 pages of the stack, therefore subtract\n    // 0x4000\n    unsafe {\n        core::arch::asm!(\n            \"mov {1:r}, gs:[{0:r}]\",\n            \"sub {1:r}, 0x4000\",\n            \"cmp rsp, {1:r}\",\n            \"ja 2f\",\n            \"call __rex_handle_stack_overflow\",\n            \"2:\",\n            in(reg) &ffi::rex_stack_ptr as *const u64 as u64,\n            lateout(reg) _,\n        );\n    }\n}\n\n#[unsafe(no_mangle)]\npub(crate) unsafe fn __rex_handle_timeout() -> ! {\n    panic!(\"Timeout in Rex program\");\n}\n\n#[unsafe(no_mangle)]\nunsafe fn __rex_handle_stack_overflow() -> ! {\n    panic!(\"Stack overflow in Rex program\");\n}\n\n// This function is called on panic.\n#[panic_handler]\nfn panic(info: &PanicInfo) -> ! {\n    // Set the termination flag\n    unsafe {\n        let termination_flag: *mut u8 = crate::per_cpu::this_cpu_ptr_mut(\n            &raw mut crate::ffi::rex_termination_state,\n        );\n        *termination_flag = 1;\n    };\n\n    unsafe { CleanupEntries::cleanup_all() };\n\n    let mut buf = LogBuf::new();\n    if write!(&mut buf, \"{}\", info).is_err() {\n        buf.reset();\n        // This string always fits in the buffer, so we ignore the Result\n        write!(&mut buf, \"unknown rust panic\").ok();\n    }\n\n    unsafe { ffi::rex_landingpad() }\n}\n"
  },
  {
    "path": "rex/src/per_cpu.rs",
    "content": "use crate::ffi;\n\npub(crate) trait PerCPURead {\n    unsafe fn this_cpu_read(addr: *const Self) -> Self;\n}\n\n// rustc does not auto-detect subregs for us\nmacro_rules! reg_template {\n    (u64) => {\n        \":r\"\n    };\n    (i64) => {\n        \":r\"\n    };\n    (u32) => {\n        \":e\"\n    };\n    (i32) => {\n        \":e\"\n    };\n    (u16) => {\n        \":x\"\n    };\n    (i16) => {\n        \":x\"\n    };\n}\n\nmacro_rules! impl_pcpu_read_integral {\n    ($t:tt $($ts:tt)*) => {\n        impl PerCPURead for $t {\n            #[inline(always)]\n            unsafe fn this_cpu_read(addr: *const Self) -> Self {\n                let mut var: Self;\n                unsafe {\n                    core::arch::asm!(\n                        concat!(\"mov {0\", reg_template!($t), \"}, gs:[{1:r}]\"),\n                        lateout(reg) var,\n                        in(reg) addr,\n                        options(readonly, nostack),\n                    );\n                }\n                var\n            }\n        }\n        impl_pcpu_read_integral!($($ts)*);\n    };\n    () => {};\n}\n\nmacro_rules! impl_pcpu_read_byte {\n    ($t:tt $($ts:tt)*) => {\n        impl PerCPURead for $t {\n            #[inline(always)]\n            unsafe fn this_cpu_read(addr: *const Self) -> Self {\n                let mut var: Self;\n                unsafe {\n                    core::arch::asm!(\n                        concat!(\"mov {0}, gs:[{1:r}]\"),\n                        lateout(reg_byte) var,\n                        in(reg) addr,\n                        options(readonly, nostack),\n                    );\n                }\n                var\n            }\n        }\n        impl_pcpu_read_byte!($($ts)*);\n    };\n    () => {};\n}\n\nmacro_rules! impl_pcpu_read_ptr {\n    ($t:tt $($ts:tt)*) => {\n        impl<T> PerCPURead for *$t T {\n            #[inline(always)]\n            unsafe fn this_cpu_read(addr: *const Self) -> Self {\n                let mut var: Self;\n                unsafe {\n                    core::arch::asm!(\n                        concat!(\"mov {0:r}, gs:[{1:r}]\"),\n                        lateout(reg) var,\n                        in(reg) addr,\n                        options(readonly, nostack),\n                    );\n                }\n                var\n            }\n        }\n        impl_pcpu_read_ptr!($($ts)*);\n    };\n    () => {};\n}\n\nimpl_pcpu_read_integral!(u64 i64 u32 i32 u16 i16);\nimpl_pcpu_read_byte!(u8 i8);\n// Mut: we have the CPU and assume no nesting\nimpl_pcpu_read_ptr!(const mut);\n\n/// For values of per-cpu variables\n#[inline(always)]\npub(crate) unsafe fn this_cpu_read<T: PerCPURead>(pcp_addr: *const T) -> T {\n    unsafe { T::this_cpu_read(pcp_addr) }\n}\n\n/// For addresses of per-cpu variables\n/// This is more expensive (in terms of # of insns)\n#[allow(dead_code)]\n#[inline(always)]\npub unsafe fn this_cpu_ptr<T>(pcp_addr: *const T) -> *const T {\n    unsafe {\n        pcp_addr.byte_add(this_cpu_read(&raw const ffi::this_cpu_off) as usize)\n    }\n}\n\n#[inline(always)]\npub unsafe fn this_cpu_ptr_mut<T>(pcp_addr: *mut T) -> *mut T {\n    unsafe {\n        pcp_addr.byte_add(this_cpu_read(&raw const ffi::this_cpu_off) as usize)\n    }\n}\n"
  },
  {
    "path": "rex/src/perf_event/mod.rs",
    "content": "mod perf_event_impl;\n\npub use perf_event_impl::*;\n"
  },
  {
    "path": "rex/src/perf_event/perf_event_impl.rs",
    "content": "use core::intrinsics::unlikely;\nuse core::marker::PhantomData;\n\nuse crate::base_helper::termination_check;\nuse crate::bindings::linux::kernel::bpf_perf_event_data_kern;\nuse crate::bindings::uapi::linux::bpf::{bpf_map_type, bpf_perf_event_value};\nuse crate::ffi;\nuse crate::linux::errno::EINVAL;\nuse crate::map::*;\nuse crate::pt_regs::PtRegs;\nuse crate::task_struct::TaskStruct;\nuse crate::utils::{to_result, NoRef, Result};\n\n#[repr(transparent)]\npub struct bpf_perf_event_data {\n    kdata: bpf_perf_event_data_kern,\n}\n\nimpl bpf_perf_event_data {\n    #[inline(always)]\n    pub fn regs(&self) -> &PtRegs {\n        unsafe { &*(self.kdata.regs as *const PtRegs) }\n    }\n\n    #[inline(always)]\n    pub fn sample_period(&self) -> u64 {\n        unsafe { (*self.kdata.data).period }\n    }\n\n    #[inline(always)]\n    pub fn addr(&self) -> u64 {\n        unsafe { (*self.kdata.data).addr }\n    }\n}\n\n#[repr(C)]\npub struct perf_event {\n    _placeholder: PhantomData<()>,\n}\n\nimpl perf_event {\n    crate::base_helper::base_helper_defs!();\n\n    pub const unsafe fn new() -> perf_event {\n        Self {\n            _placeholder: PhantomData,\n        }\n    }\n\n    pub unsafe fn convert_ctx(\n        &self,\n        ctx: *mut (),\n    ) -> &'static bpf_perf_event_data {\n        unsafe { &*(ctx as *mut bpf_perf_event_data) }\n    }\n\n    pub fn bpf_perf_prog_read_value(\n        &self,\n        ctx: &bpf_perf_event_data,\n        buf: &mut bpf_perf_event_value,\n    ) -> Result {\n        let size = core::mem::size_of::<bpf_perf_event_value>() as u32;\n        let ctx_kptr = ctx as *const bpf_perf_event_data\n            as *const bpf_perf_event_data_kern;\n\n        termination_check!(unsafe {\n            to_result!(ffi::bpf_perf_prog_read_value(ctx_kptr, buf, size))\n        })\n    }\n\n    pub fn bpf_get_stackid_pe<K, V>(\n        &self,\n        ctx: &bpf_perf_event_data,\n        map: &'static RexStackTrace<K, V>,\n        flags: u64,\n    ) -> Result\n    where\n        V: Copy + NoRef,\n    {\n        let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) };\n        if unlikely(map_kptr.is_null()) {\n            return Err(EINVAL as i32);\n        }\n\n        let ctx_kptr = ctx as *const bpf_perf_event_data\n            as *const bpf_perf_event_data_kern;\n\n        termination_check!(unsafe {\n            to_result!(ffi::bpf_get_stackid_pe(ctx_kptr, map_kptr, flags))\n        })\n    }\n\n    pub fn bpf_get_current_task(&self) -> Option<TaskStruct> {\n        TaskStruct::get_current_task()\n    }\n}\n"
  },
  {
    "path": "rex/src/pt_regs.rs",
    "content": "use paste::paste;\n\nuse crate::bindings::linux::kernel::pt_regs;\n\n/// Transparently wraps around the kernel-internal `struct pt_regs` and make the\n/// fields read-only to prevent user-defined code from modifying the registers\n#[repr(transparent)]\npub struct PtRegs {\n    pub(crate) regs: pt_regs,\n}\n\nmacro_rules! decl_reg_accessors_1 {\n    ($t:ident $($ts:ident)*) => {\n        #[inline(always)]\n        pub fn $t(&self) -> u64 {\n            self.regs.$t\n        }\n        decl_reg_accessors_1!($($ts)*);\n    };\n    () => {};\n}\n\nmacro_rules! decl_reg_accessors_2 {\n    ($t:ident $($ts:ident)*) => {\n        paste! {\n            #[inline(always)]\n            pub fn [<r $t>](&self) -> u64 {\n                self.regs.$t\n            }\n        }\n        decl_reg_accessors_2!($($ts)*);\n    };\n    () => {};\n}\n\nmacro_rules! decl_reg_accessors {\n    ($t1:ident $($ts1:ident)*, $t2:ident $($ts2:ident)*) => {\n        // regs that does not require special handling\n        decl_reg_accessors_1!($t1 $($ts1)*);\n        // regs that does not have the 'r' prefix in kernel pt_regs\n        decl_reg_accessors_2!($t2 $($ts2)*);\n    }\n}\n\nimpl PtRegs {\n    decl_reg_accessors!(r15 r14 r13 r12 r11 r10 r9 r8,\n                        bp bx ax cx dx si di ip sp);\n\n    // orig_rax cs eflags ss cannot be batch-processed by macros\n    #[inline(always)]\n    pub fn orig_rax(&self) -> u64 {\n        self.regs.orig_ax\n    }\n\n    #[inline(always)]\n    pub fn cs(&self) -> u64 {\n        unsafe { self.regs.__bindgen_anon_1.cs as u64 }\n    }\n\n    #[inline(always)]\n    pub fn eflags(&self) -> u64 {\n        self.regs.flags\n    }\n\n    #[inline(always)]\n    pub fn ss(&self) -> u64 {\n        unsafe { self.regs.__bindgen_anon_2.ss as u64 }\n    }\n}\n"
  },
  {
    "path": "rex/src/random32.rs",
    "content": "use crate::ffi;\n\n// fn get_cpu_var()\n#[inline(always)]\npub(crate) fn bpf_user_rnd_u32() -> u32 {\n    // directly use get_random_u32\n    unsafe { ffi::get_random_u32() }\n}\n"
  },
  {
    "path": "rex/src/sched_cls/mod.rs",
    "content": "// mod binding;\nmod sched_cls_impl;\n\npub use sched_cls_impl::*;\n"
  },
  {
    "path": "rex/src/sched_cls/sched_cls_impl.rs",
    "content": "use core::ffi::{c_char, c_uchar};\nuse core::marker::PhantomData;\nuse core::{mem, slice};\n\nuse crate::base_helper::termination_check;\nuse crate::bindings::linux::kernel::{\n    ethhdr, iphdr, sk_buff, sock, tcphdr, udphdr,\n};\nuse crate::bindings::uapi::linux::bpf::bpf_map_type;\npub use crate::bindings::uapi::linux::pkt_cls::{\n    TC_ACT_OK, TC_ACT_REDIRECT, TC_ACT_SHOT,\n};\nuse crate::ffi;\nuse crate::utils::*;\n\npub struct __sk_buff<'a> {\n    pub data_slice: &'a mut [c_uchar],\n    kptr: &'static mut sk_buff,\n}\n\n// Define accessors of program-accessible fields\n// TODO: may need to append more based on __sk_buff\nimpl<'a> __sk_buff<'a> {\n    #[inline(always)]\n    pub fn len(&self) -> u32 {\n        self.kptr.len\n    }\n\n    #[inline(always)]\n    pub fn data_len(&self) -> u32 {\n        self.kptr.data_len\n    }\n\n    #[inline(always)]\n    pub fn protocol(&self) -> u16be {\n        u16be(unsafe {\n            (self.kptr.__bindgen_anon_4.__bindgen_anon_1)\n                .as_ref()\n                .protocol\n        })\n    }\n\n    #[inline(always)]\n    pub fn priority(&self) -> u32 {\n        unsafe {\n            (self.kptr.__bindgen_anon_4.__bindgen_anon_1)\n                .as_ref()\n                .priority\n        }\n    }\n\n    #[inline(always)]\n    // TODO: may need to update based on __sk_buff\n    pub fn ingress_ifindex(&self) -> u32 {\n        0\n    }\n\n    #[inline(always)]\n    pub fn ifindex(&self) -> u32 {\n        unsafe {\n            (*self\n                .kptr\n                .__bindgen_anon_1\n                .__bindgen_anon_1\n                .__bindgen_anon_1\n                .dev)\n                .ifindex as u32\n        }\n    }\n\n    #[inline(always)]\n    pub fn hash(&self) -> u32 {\n        unsafe { (self.kptr.__bindgen_anon_4.__bindgen_anon_1).as_ref().hash }\n    }\n\n    #[inline(always)]\n    // TODO: may need to update based on __sk_buff\n    pub fn mark(&self) -> u32 {\n        0\n    }\n\n    #[inline(always)]\n    // TODO: may need to update based on __sk_buff\n    pub fn pkt_type(&self) -> u32 {\n        0\n    }\n\n    #[inline(always)]\n    // TODO: may need to update based on __sk_buff\n    pub fn queue_mapping(&self) -> u16 {\n        self.kptr.queue_mapping\n    }\n\n    #[inline(always)]\n    // TODO: may need to update based on __sk_buff\n    pub fn vlan_present(&self) -> u32 {\n        0\n    }\n\n    #[inline(always)]\n    // TODO: may need to update based on __sk_buff\n    pub fn vlan_tci(&self) -> u16 {\n        unsafe {\n            self.kptr\n                .__bindgen_anon_4\n                .__bindgen_anon_1\n                .as_ref()\n                .__bindgen_anon_2\n                .__bindgen_anon_1\n                .vlan_tci\n        }\n    }\n\n    #[inline(always)]\n    pub fn vlan_proto(&self) -> u16be {\n        u16be(unsafe {\n            self.kptr\n                .__bindgen_anon_4\n                .__bindgen_anon_1\n                .as_ref()\n                .__bindgen_anon_2\n                .__bindgen_anon_1\n                .vlan_proto\n        })\n    }\n\n    #[inline(always)]\n    pub fn cb(&self) -> [c_char; 20] {\n        let mut cb = [0; 20];\n        cb[0..20].clone_from_slice(&self.kptr.cb[0..20]);\n        cb\n    }\n\n    #[inline(always)]\n    // TODO: may need to update based on __sk_buff\n    pub fn tc_classid(&self) -> u32 {\n        0\n    }\n\n    #[inline(always)]\n    pub fn tc_index(&self) -> u16 {\n        unsafe {\n            (self.kptr.__bindgen_anon_4.__bindgen_anon_1)\n                .as_ref()\n                .tc_index\n        }\n    }\n\n    #[inline(always)]\n    // TODO: may need to update based on __sk_buff\n    pub fn napi_id(&self) -> u32 {\n        0\n    }\n\n    #[inline(always)]\n    // TODO: may need to update based on __sk_buff\n    pub fn data_meta(&self) -> u32 {\n        0\n    }\n\n    #[inline(always)]\n    pub fn sk(&self) -> &'a sock {\n        unsafe { &*self.kptr.sk }\n    }\n}\n\n#[repr(C)]\npub struct sched_cls {\n    _placeholder: PhantomData<()>,\n}\n\nimpl sched_cls {\n    crate::base_helper::base_helper_defs!();\n\n    pub const unsafe fn new() -> sched_cls {\n        Self {\n            _placeholder: PhantomData,\n        }\n    }\n\n    // NOTE: copied from xdp impl, may change in the future\n    #[inline(always)]\n    pub fn eth_header<'b>(\n        &self,\n        skb: &'b mut __sk_buff,\n    ) -> AlignedMut<'b, ethhdr> {\n        convert_slice_to_struct_mut::<ethhdr>(\n            &mut skb.data_slice[0..mem::size_of::<ethhdr>()],\n        )\n    }\n\n    #[inline(always)]\n    pub fn udp_header<'b>(\n        &self,\n        skb: &'b mut __sk_buff,\n    ) -> AlignedMut<'b, udphdr> {\n        // NOTE: this assumes packet has ethhdr and iphdr\n        let begin = mem::size_of::<ethhdr>() + mem::size_of::<iphdr>();\n        let end = mem::size_of::<udphdr>() + begin;\n\n        convert_slice_to_struct_mut::<udphdr>(&mut skb.data_slice[begin..end])\n    }\n\n    #[inline(always)]\n    pub fn tcp_header<'b>(\n        &self,\n        skb: &'b mut __sk_buff,\n    ) -> AlignedMut<'b, tcphdr> {\n        // NOTE: this assumes packet has ethhdr and iphdr\n        let begin = mem::size_of::<ethhdr>() + mem::size_of::<iphdr>();\n        let end = mem::size_of::<tcphdr>() + begin;\n\n        convert_slice_to_struct_mut::<tcphdr>(&mut skb.data_slice[begin..end])\n    }\n\n    #[inline(always)]\n    pub fn ip_header<'b>(\n        &self,\n        skb: &'b mut __sk_buff,\n    ) -> AlignedMut<'b, iphdr> {\n        // NOTE: this assumes packet has ethhdr\n        let begin = mem::size_of::<ethhdr>();\n        let end = mem::size_of::<iphdr>() + begin;\n\n        convert_slice_to_struct_mut::<iphdr>(&mut skb.data_slice[begin..end])\n    }\n\n    #[inline(always)]\n    pub fn bpf_clone_redirect(\n        &self,\n        skb: &mut __sk_buff,\n        ifindex: u32,\n        flags: u64,\n    ) -> Result {\n        let ret = termination_check!(unsafe {\n            ffi::bpf_clone_redirect(skb.kptr, ifindex, flags)\n        });\n\n        if ret != 0 {\n            return Err(ret);\n        }\n\n        // WARN: bpf_clone_redirect does not update skb.kptr?\n        skb.data_slice = unsafe {\n            slice::from_raw_parts_mut(\n                skb.kptr.data as *mut c_uchar,\n                skb.len() as usize,\n            )\n        };\n\n        Ok(0)\n    }\n\n    // Now returns a mutable ref, but since every reg is private the user prog\n    // cannot change reg contents. The user should not be able to directly\n    // assign this reference a new value either, given that they will not able\n    // to create another instance of pt_regs (private fields, no pub ctor)\n    #[inline(always)]\n    pub unsafe fn convert_ctx(&self, ctx: *mut ()) -> __sk_buff<'_> {\n        let kptr = unsafe { &mut *(ctx as *mut sk_buff) };\n\n        // NOTE: not support jumobo frame yet with non-linear sk_buff\n        let data_length = (kptr.len - kptr.data_len) as usize;\n\n        let data_slice = unsafe {\n            slice::from_raw_parts_mut(kptr.data as *mut c_uchar, data_length)\n        };\n\n        __sk_buff { data_slice, kptr }\n    }\n}\n"
  },
  {
    "path": "rex/src/spinlock.rs",
    "content": "use crate::base_helper::termination_check;\npub use crate::bindings::uapi::linux::bpf::bpf_spin_lock;\nuse crate::ffi;\nuse crate::panic::CleanupEntries;\n\n/// An RAII implementation of a \"scoped lock\" of a bpf spinlock. When this\n/// structure is dropped (falls out of scope), the lock will be unlocked.\n///\n/// Ref: <https://doc.rust-lang.org/src/std/sync/mutex.rs.html#206-209>\n#[must_use = \"if unused the spinlock will immediately unlock\"]\n#[clippy::has_significant_drop]\npub struct rex_spinlock_guard<'a> {\n    lock: &'a mut bpf_spin_lock,\n    cleanup_idx: usize,\n}\n\nimpl<'a> rex_spinlock_guard<'a> {\n    /// Constructor function that locks the spinlock\n    pub fn new(lock: &'a mut bpf_spin_lock) -> Self {\n        termination_check!({\n            // Put it before lock so if it panics we will not be holding the\n            // lock without a valid cleanup entry for it\n            let cleanup_idx = CleanupEntries::register_cleanup(\n                Self::panic_cleanup,\n                lock as *mut bpf_spin_lock as *mut (),\n            );\n\n            // Lock\n            unsafe { ffi::bpf_spin_lock(lock) };\n\n            Self { lock, cleanup_idx }\n        })\n    }\n\n    /// Function that unlocks the spinlock, used by cleanup list and drop\n    pub(crate) unsafe fn panic_cleanup(lock: *mut ()) {\n        unsafe {\n            ffi::bpf_spin_unlock(lock as *mut bpf_spin_lock);\n        }\n    }\n}\n\nimpl Drop for rex_spinlock_guard<'_> {\n    /// Unlock the spinlock when the guard is out-of-scope\n    fn drop(&mut self) {\n        termination_check!({\n            // Put it before unlock so if it panics we will not unlock twice\n            // (once here in the drop handler, the other in the\n            // panic handler triggered by this function)\n            CleanupEntries::deregister_cleanup(self.cleanup_idx);\n\n            // Unlock\n            unsafe { ffi::bpf_spin_unlock(self.lock) };\n        })\n    }\n}\n\n/// Unimplement Send and Sync\n/// Ref: <https://doc.rust-lang.org/nomicon/send-and-sync.html>\nimpl !Send for rex_spinlock_guard<'_> {}\nimpl !Sync for rex_spinlock_guard<'_> {}\n"
  },
  {
    "path": "rex/src/task_struct.rs",
    "content": "use core::ffi::{self as core_ffi, CStr};\nuse core::ops::Deref;\n\nuse crate::base_helper::termination_check;\nuse crate::bindings::linux::kernel::task_struct;\nuse crate::ffi;\nuse crate::panic::CleanupEntries;\nuse crate::per_cpu::this_cpu_read;\nuse crate::pt_regs::PtRegs;\n\n// Bindgen has problem generating these constants\nconst TOP_OF_KERNEL_STACK_PADDING: u64 = 0;\nconst PAGE_SHIFT: u64 = 12;\nconst PAGE_SIZE: u64 = 1u64 << PAGE_SHIFT;\nconst THREAD_SIZE_ORDER: u64 = 2; // assume no kasan\nconst THREAD_SIZE: u64 = PAGE_SIZE << THREAD_SIZE_ORDER;\n\npub struct TaskStruct {\n    // struct task_struct * should always live longer than program execution\n    // given the RCU read lock\n    task: &'static task_struct,\n    kptr: *mut task_struct,\n}\n\nimpl TaskStruct {\n    pub(crate) fn get_current_task() -> Option<Self> {\n        let current: *mut task_struct =\n            unsafe { this_cpu_read(&raw const ffi::current_task) };\n\n        if current.is_null() {\n            None\n        } else {\n            Some(TaskStruct {\n                task: unsafe { &*current },\n                kptr: current,\n            })\n        }\n    }\n\n    #[inline(always)]\n    pub fn get_pid(&self) -> i32 {\n        self.task.pid\n    }\n\n    #[inline(always)]\n    pub fn get_tgid(&self) -> i32 {\n        self.task.tgid\n    }\n\n    #[inline(always)]\n    pub fn get_utime(&self) -> u64 {\n        self.task.utime\n    }\n\n    // Design decision: the equivalent BPF helper writes the program name to\n    // a user-provided buffer, here we can take advantage of Rust's ownership by\n    // just providing a &CStr instead\n    pub fn get_comm(&self) -> Result<&CStr, core_ffi::FromBytesUntilNulError> {\n        // casting from c_char to u8 is sound, see:\n        // https://doc.rust-lang.org/src/core/ffi/c_str.rs.html#264\n        let comm_bytes =\n            unsafe { &*(&self.task.comm[..] as *const _ as *const [u8]) };\n        CStr::from_bytes_until_nul(comm_bytes)\n    }\n\n    pub fn get_pt_regs(&self) -> &'static PtRegs {\n        // X86 specific\n        // stack_top is actually bottom of the kernel stack, it refers to the\n        // highest address of the stack pages\n        let stack_top =\n            self.task.stack as u64 + THREAD_SIZE - TOP_OF_KERNEL_STACK_PADDING;\n        let reg_addr = stack_top - core::mem::size_of::<PtRegs>() as u64;\n        // The pt_regs should always be on the top of the stack\n        unsafe { &*(reg_addr as *const PtRegs) }\n    }\n}\n\npub struct OwnedTaskStruct {\n    inner: TaskStruct,\n    cleanup_idx: usize,\n}\n\nimpl OwnedTaskStruct {\n    pub fn from_pid(pid: i32) -> Option<Self> {\n        termination_check!({\n            let task = unsafe { ffi::bpf_task_from_pid(pid) };\n\n            if task.is_null() {\n                None\n            } else {\n                let cleanup_idx = CleanupEntries::register_cleanup(\n                    Self::panic_cleanup,\n                    task as *mut (),\n                );\n\n                Some(Self {\n                    inner: TaskStruct {\n                        task: unsafe { &*task },\n                        kptr: task,\n                    },\n                    cleanup_idx,\n                })\n            }\n        })\n    }\n\n    pub(crate) unsafe fn panic_cleanup(task: *mut ()) {\n        unsafe {\n            ffi::bpf_task_release(task as *mut task_struct);\n        }\n    }\n}\n\nimpl Deref for OwnedTaskStruct {\n    type Target = TaskStruct;\n\n    fn deref(&self) -> &Self::Target {\n        &self.inner\n    }\n}\n\nimpl Drop for OwnedTaskStruct {\n    fn drop(&mut self) {\n        termination_check!({\n            unsafe {\n                CleanupEntries::deregister_cleanup(self.cleanup_idx);\n                ffi::bpf_task_release(self.inner.kptr);\n            }\n        })\n    }\n}\n"
  },
  {
    "path": "rex/src/tracepoint/binding.rs",
    "content": "#[repr(C)]\n#[derive(Debug, Copy, Clone)]\npub struct SyscallsEnterOpenCtx {\n    unused: u64,\n    pub syscall_nr: i64,\n    pub filename_ptr: i64,\n    pub flags: i64,\n    pub mode: i64,\n}\n\n#[repr(C)]\n#[derive(Debug, Copy, Clone)]\npub struct SyscallsEnterOpenatCtx {\n    unused: u64,\n    pub syscall_nr: i64,\n    pub dfd: i64,\n    pub filename_ptr: i64,\n    pub flags: i64,\n    pub mode: i64,\n}\n\n#[repr(C)]\n#[derive(Debug, Copy, Clone)]\npub struct SyscallsExitOpenCtx {\n    unused: u64,\n    pub syscall_nr: i64,\n    pub ret: i64,\n}\n\n#[repr(C)]\n#[derive(Debug, Copy, Clone)]\npub struct SyscallsExitOpenatCtx {\n    unused: u64,\n    pub syscall_nr: i64,\n    pub ret: i64,\n}\n\n#[repr(C)]\n#[derive(Debug, Copy, Clone)]\npub struct SyscallsEnterDupCtx {\n    unused: u64,\n    pub syscall_nr: i64,\n    pub fildes: u64,\n}\n\n#[repr(C)]\n#[derive(Debug, Copy, Clone)]\npub struct RawSyscallsEnterCtx {\n    unused: u64,\n    pub id: i64,\n    pub args: [u64; 6],\n}\n\n#[repr(C)]\n#[derive(Debug, Copy, Clone)]\npub struct RawSyscallsExitCtx {\n    unused: u64,\n    pub id: i64,\n    pub ret: i64,\n}\n"
  },
  {
    "path": "rex/src/tracepoint/mod.rs",
    "content": "mod binding;\nmod tp_impl;\n\npub use binding::*;\npub use tp_impl::*;\n"
  },
  {
    "path": "rex/src/tracepoint/tp_impl.rs",
    "content": "use core::marker::PhantomData;\n\nuse super::{\n    RawSyscallsEnterCtx, RawSyscallsExitCtx, SyscallsEnterDupCtx,\n    SyscallsEnterOpenCtx, SyscallsEnterOpenatCtx, SyscallsExitOpenCtx,\n    SyscallsExitOpenatCtx,\n};\nuse crate::base_helper::termination_check;\nuse crate::bindings::uapi::linux::bpf::bpf_map_type;\nuse crate::map::RexPerfEventArray;\nuse crate::task_struct::TaskStruct;\nuse crate::utils::sealed::PerfEventStreamerBase;\nuse crate::utils::{to_result, NoRef, PerfEventMaskedCPU, PerfEventStreamer};\nuse crate::{ffi, Result};\n\npub trait TracepointContext {}\nimpl TracepointContext for SyscallsEnterOpenCtx {}\nimpl TracepointContext for SyscallsEnterOpenatCtx {}\nimpl TracepointContext for SyscallsExitOpenCtx {}\nimpl TracepointContext for SyscallsExitOpenatCtx {}\nimpl TracepointContext for SyscallsEnterDupCtx {}\nimpl TracepointContext for RawSyscallsEnterCtx {}\nimpl TracepointContext for RawSyscallsExitCtx {}\n\n#[repr(C)]\npub struct tracepoint<C: TracepointContext + 'static> {\n    _placeholder: PhantomData<C>,\n}\n\nimpl<C: TracepointContext + 'static> tracepoint<C> {\n    crate::base_helper::base_helper_defs!();\n\n    pub const unsafe fn new() -> tracepoint<C> {\n        Self {\n            _placeholder: PhantomData,\n        }\n    }\n\n    pub unsafe fn convert_ctx(&self, ctx: *mut ()) -> &'static C {\n        unsafe { &*(ctx as *mut C) }\n    }\n\n    pub fn bpf_get_current_task(&self) -> Option<TaskStruct> {\n        TaskStruct::get_current_task()\n    }\n}\n\nimpl<C: TracepointContext + 'static> PerfEventStreamerBase for tracepoint<C> {}\n\nimpl<C: TracepointContext + 'static> PerfEventStreamer for tracepoint<C> {\n    type Context = C;\n\n    fn output_event<T: Copy + NoRef>(\n        &self,\n        ctx: &Self::Context,\n        map: &'static RexPerfEventArray<T>,\n        data: &T,\n        cpu: PerfEventMaskedCPU,\n    ) -> Result {\n        let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) };\n        let ctx_ptr = ctx as *const C as *const ();\n        termination_check!(unsafe {\n            to_result!(ffi::bpf_perf_event_output_tp(\n                ctx_ptr,\n                map_kptr,\n                cpu.masked_cpu,\n                data as *const T as *const (),\n                core::mem::size_of::<T>() as u64\n            ))\n        })\n    }\n}\n"
  },
  {
    "path": "rex/src/utils.rs",
    "content": "use core::ffi::{c_int, c_uchar};\nuse core::mem;\nuse core::ops::{Deref, DerefMut, Drop};\n\nuse crate::bindings::uapi::linux::bpf::{BPF_F_CURRENT_CPU, BPF_F_INDEX_MASK};\nuse crate::map::RexPerfEventArray;\n\n#[repr(transparent)]\n#[derive(Copy, Clone)]\npub struct u16be(pub(crate) u16);\n\nimpl From<u16be> for u16 {\n    // Required method\n    fn from(value: u16be) -> Self {\n        u16::from_be(value.0)\n    }\n}\n\n/// A specialized Result for typical int return value in the kernel\n///\n/// To be used as the return type for functions that may fail.\n///\n/// Ref: linux/rust/kernel/error.rs\npub type Result = core::result::Result<c_int, c_int>;\n\n/// Converts an integer as returned by a C kernel function to an error if it's\n/// negative, and `Ok(val)` otherwise.\n///\n/// Ref: linux/rust/kernel/error.rs\n// genetic specialization to Macro\n#[macro_export]\nmacro_rules! to_result {\n    ($retval:expr) => {{\n        let val = $retval;\n        if val < 0 {\n            Err(val as i32)\n        } else {\n            Ok(val as i32)\n        }\n    }};\n}\npub(crate) use to_result;\n\n/// A marker trait that prevents derivation on types that contain references or\n/// raw pointers. This avoids accidental dereference of invalid pointers in\n/// foreign objects obtained from the kernel (e.g. via `bpf_map_lookup_elem` or\n/// `bpf_probe_read_kernel`).\n///\n/// Though dererferencing raw pointers are not possible in Rex programs as it\n/// requires `unsafe`, we still need to consider the case where a core library\n/// type wraps the unsafe deref operation under a safe interface (an example is\n/// `core::slice::Iter`).\npub unsafe auto trait NoRef {}\nimpl<T: ?Sized> !NoRef for &T {}\nimpl<T: ?Sized> !NoRef for &mut T {}\nimpl<T: ?Sized> !NoRef for *const T {}\nimpl<T: ?Sized> !NoRef for *mut T {}\n\n/// An enum used internally by `Aligned` and `AlignedMut`, the encapsulated\n/// value is either a reference to the data if the aligned requirement is\n/// satisfied, or a copied value of the data if it is not aligned and a\n/// reference cannot be taken directly.\nenum AlignedInner<RefT, ValT> {\n    Ref(RefT),\n    Val(ValT),\n}\n\n/// An abstraction over a `&T` for both aligned and unaligned accesses. This\n/// struct can be constructed with [`convert_slice_to_struct`] from an\n/// underlying data slice. The underlying data is either a direct `&'a T` by\n/// reborrowing the slice or a copied value of `T` from the slice, depending on\n/// whether the slice pointer is properly aligned for `T`.\n///\n/// The abstraction provided by this struct is a shared reference, for an\n/// abstraction over mutable references, use [`AlignedMut`].\npub struct Aligned<'a, T> {\n    inner: AlignedInner<&'a T, T>,\n}\n\nimpl<'a, T> Aligned<'a, T> {\n    /// Constructs an `Aligned<'a, T>` from an aligned reference.\n    #[inline(always)]\n    pub(crate) const fn from_ref(aligned_ref: &'a T) -> Self {\n        Self {\n            inner: AlignedInner::Ref(aligned_ref),\n        }\n    }\n\n    /// Constructs an `Aligned<'a, T>` from a copied value of `T` to handle\n    /// unaligned cases.\n    #[inline(always)]\n    pub(crate) const fn from_val(copied_val: T) -> Self {\n        Self {\n            inner: AlignedInner::Val(copied_val),\n        }\n    }\n}\n\n/// Allows users of `Aligned<'_, T>` to transparently access the value behind\n/// the reference abstraction.\nimpl<T> Deref for Aligned<'_, T> {\n    type Target = T;\n\n    /// If the underlying data is a `&T`, it is directly returned;\n    /// otherwise a shared reference to the copied value of `T` is taken and\n    /// returned.\n    #[inline(always)]\n    fn deref(&self) -> &Self::Target {\n        match &self.inner {\n            AlignedInner::Ref(aligned_ref) => aligned_ref,\n            AlignedInner::Val(ref unaligned_val) => unaligned_val,\n        }\n    }\n}\n\n/// An abstraction over a `&mut T` for both aligned and unaligned accesses. This\n/// struct can be constructed with [`convert_slice_to_struct_mut`] from an\n/// underlying data slice. The underlying data is either a direct `&'a mut T` by\n/// reborrowing the slice or a copied value of `T` from the slice, depending on\n/// whether the slice pointer is properly aligned for `T`. In the unaligned\n/// case, the mutable reference to slice is also stored in this struct.\n///\n/// The abstraction provided by this struct is a mutable reference, for an\n/// abstraction over shared references, use [`Aligned`].\npub struct AlignedMut<'a, T: Copy> {\n    inner: AlignedInner<&'a mut T, (T, &'a mut [c_uchar])>,\n}\n\nimpl<'a, T: Copy> AlignedMut<'a, T> {\n    /// Constructs an `AlignedMut<'a, T>` from an aligned reference.\n    #[inline(always)]\n    pub(crate) const fn from_ref(aligned_ref: &'a mut T) -> Self {\n        Self {\n            inner: AlignedInner::Ref(aligned_ref),\n        }\n    }\n\n    /// Constructs an `AlignedMut<'a, T>` from a copied value of `T` and the\n    /// original mutable reference to slice to handle unaligned cases.\n    #[inline(always)]\n    pub(crate) const fn from_val(\n        copied_val: T,\n        slice: &'a mut [c_uchar],\n    ) -> Self {\n        Self {\n            inner: AlignedInner::Val((copied_val, slice)),\n        }\n    }\n}\n\n/// Allows users of `AlignedMut<'_, T>` to transparently access the value behind\n/// the reference abstraction.\nimpl<T: Copy> Deref for AlignedMut<'_, T> {\n    type Target = T;\n\n    /// If the underlying data is a `&mut T`, the coerced `&T` is returned;\n    /// otherwise a shared reference to the copied value of `T` is taken and\n    /// returned.\n    #[inline(always)]\n    fn deref(&self) -> &Self::Target {\n        match &self.inner {\n            AlignedInner::Ref(aligned_ref) => aligned_ref,\n            AlignedInner::Val(ref unaligned_val) => &unaligned_val.0,\n        }\n    }\n}\n\n/// Allows users of `AlignedMut<'_, T>` to transparently access and mutate the\n/// value behind the reference abstraction.\nimpl<T: Copy> DerefMut for AlignedMut<'_, T> {\n    /// If the underlying data is a `&mut T`, it is directly returned;\n    /// otherwise a mutable reference to the copied value of `T` is taken and\n    /// returned.\n    #[inline(always)]\n    fn deref_mut(&mut self) -> &mut Self::Target {\n        match &mut self.inner {\n            AlignedInner::Ref(aligned_ref) => aligned_ref,\n            AlignedInner::Val(ref mut unaligned_val) => &mut unaligned_val.0,\n        }\n    }\n}\n\n/// Drop handler to support automatic writeback to the original data slice\nimpl<T: Copy> Drop for AlignedMut<'_, T> {\n    #[inline(always)]\n    fn drop(&mut self) {\n        if let AlignedInner::Val(ref mut unaligned_val) = self.inner {\n            unsafe {\n                (unaligned_val.1.as_mut_ptr() as *mut T)\n                    .write_unaligned(unaligned_val.0);\n            }\n        }\n    }\n}\n\n/// Converts the bytes in `slice` into a `&T` abstracted by [`Aligned<'_, T>`].\n/// This is only performed on the first `core::mem::size_of::<T>()` bytes.\n/// If the slice is not long enough, this function panics.\n///\n/// If `slice.as_ptr()` is properly aligned for `T`, the pointer is reborrowed\n/// into a `&T` and stored in the returned `Aligned<'_, T>`.\n/// If the pointer does not satisfy the alignment requirement of `T`, this\n/// function copies the value via `core::ptr::read_unaligned` and stores it in\n/// the returned `Aligned<'_, T>`.\n///\n/// The [operation][read_unaligned_doc] performed in the unaligned case implies\n/// that `T` has to be [`Copy`].\n///\n/// [read_unaligned_doc]: https://doc.rust-lang.org/core/ptr/fn.read_unaligned.html\n#[inline]\npub fn convert_slice_to_struct<T>(slice: &[c_uchar]) -> Aligned<'_, T>\nwhere\n    T: Copy + NoRef,\n{\n    assert!(\n        slice.len() >= mem::size_of::<T>(),\n        \"size mismatch in convert_slice_to_struct\"\n    );\n\n    let ptr = slice.as_ptr() as *const T;\n\n    if ptr.is_aligned() {\n        unsafe { Aligned::from_ref(&*ptr) }\n    } else {\n        unsafe { Aligned::from_val(ptr.read_unaligned()) }\n    }\n}\n\n/// Converts the bytes in `slice` into a `&mut T` abstracted by\n/// [`AlignedMut<'_, T>`].\n/// This is only performed on the first `core::mem::size_of::<T>()` bytes.\n/// If the slice is not long enough, this function panics.\n///\n/// If `slice.as_mut_ptr()` is properly aligned for `T`, the pointer is\n/// reborrowed into a `&mut T` and stored in the returned `AlignedMut<'_, T>`.\n/// If the pointer does not satisfy the alignment requirement of `T`, this\n/// function copies the value via `core::ptr::read_unaligned` and stores it in\n/// the returned `AlignedMut<'_, T>`.\n///\n/// The [operation][read_unaligned_doc] performed in the unaligned case implies\n/// that `T` has to be [`Copy`].\n///\n/// [read_unaligned_doc]: https://doc.rust-lang.org/core/ptr/fn.read_unaligned.html\n#[inline]\npub fn convert_slice_to_struct_mut<T>(\n    slice: &mut [c_uchar],\n) -> AlignedMut<'_, T>\nwhere\n    T: Copy + NoRef,\n{\n    assert!(\n        slice.len() >= mem::size_of::<T>(),\n        \"size mismatch in convert_slice_to_struct_mut\"\n    );\n\n    let ptr = slice.as_mut_ptr() as *mut T;\n\n    if ptr.is_aligned() {\n        unsafe { AlignedMut::from_ref(&mut *ptr) }\n    } else {\n        unsafe { AlignedMut::from_val(ptr.read_unaligned(), slice) }\n    }\n}\n\n/// Read a numeric field that is stored **big-endian** inside a header already\n/// sitting in `payload_slice` at offset `hdr_base`.\n///\n/// Example:\n/// ```\n/// let iphdr_base = size_of::<ethhdr>();\n/// let proto_be = read_field!(skb.data_slice, iphdr_base, iphdr, protocol, u8);\n/// match u8::from_be(proto_be) as u32 {\n///     IPPROTO_TCP => handle_tcp(),\n///     IPPROTO_UDP => handle_udp(),\n///     _  => {}\n/// }\n/// ```\n#[macro_export]\nmacro_rules! read_field {\n    ($slice:expr,     // payload slice\n     $hdr_base:expr,  // where this header starts inside the buffer\n     $hdr:path,       // concrete header type, for `offset_of!`\n     $field:ident,    // field we want\n     $ty:ty           // Rust type of that field (u8, u16, …)\n    ) => {{\n        let start = $hdr_base + core::mem::offset_of!($hdr, $field);\n        *$crate::utils::convert_slice_to_struct::<$ty>(\n            &$slice[start..start + size_of::<$ty>()],\n        )\n    }};\n}\n\npub(crate) mod sealed {\n    pub trait PerfEventStreamerBase {}\n}\n\n// For implementers, see tp_impl.rs for how to implement\n// this trait\n/// Programs that can stream data through a\n/// RexPerfEventArray will implement this trait\npub trait PerfEventStreamer: sealed::PerfEventStreamerBase {\n    type Context;\n    fn output_event<T: Copy + NoRef>(\n        &self,\n        ctx: &Self::Context,\n        map: &'static RexPerfEventArray<T>,\n        data: &T,\n        cpu: PerfEventMaskedCPU,\n    ) -> Result;\n}\n\n/// Newtype for a cpu for perf event output to ensure\n/// type safety since the cpu must be masked with\n/// BPF_F_INDEX_MASK\n#[derive(Debug, Copy, Clone)]\npub struct PerfEventMaskedCPU {\n    pub(crate) masked_cpu: u64,\n}\n\nimpl PerfEventMaskedCPU {\n    pub fn current_cpu() -> Self {\n        PerfEventMaskedCPU {\n            masked_cpu: BPF_F_CURRENT_CPU,\n        }\n    }\n\n    pub fn any_cpu(cpu: u64) -> Self {\n        PerfEventMaskedCPU {\n            masked_cpu: cpu & BPF_F_INDEX_MASK,\n        }\n    }\n}\n"
  },
  {
    "path": "rex/src/xdp/mod.rs",
    "content": "// mod binding;\nmod xdp_impl;\n\npub use xdp_impl::*;\n"
  },
  {
    "path": "rex/src/xdp/xdp_impl.rs",
    "content": "use core::ffi::c_uchar;\nuse core::marker::PhantomData;\nuse core::mem::size_of;\nuse core::{mem, slice};\n\nuse crate::base_helper::termination_check;\npub use crate::bindings::linux::kernel::{\n    ethhdr, iphdr, tcphdr, udphdr, xdp_buff,\n};\nuse crate::bindings::uapi::linux::bpf::bpf_map_type;\n// expose the following constants to the user\npub use crate::bindings::uapi::linux::bpf::{\n    XDP_ABORTED, XDP_DROP, XDP_PASS, XDP_REDIRECT, XDP_TX,\n};\npub use crate::bindings::uapi::linux::r#in::{IPPROTO_TCP, IPPROTO_UDP};\nuse crate::ffi;\nuse crate::utils::*;\n\nimpl iphdr {\n    #[inline(always)]\n    pub fn saddr(&mut self) -> &mut u32 {\n        unsafe { &mut self.__bindgen_anon_1.__bindgen_anon_1.saddr }\n    }\n\n    pub fn daddr(&mut self) -> &mut u32 {\n        unsafe { &mut self.__bindgen_anon_1.__bindgen_anon_1.daddr }\n    }\n}\n\n#[inline(always)]\npub fn compute_ip_checksum(ip_header: &mut iphdr) -> u16 {\n    let mut sum: u32 = 0;\n    ip_header.check = 0;\n\n    let count = size_of::<iphdr>() >> 1;\n\n    let u16_slice = unsafe {\n        core::slice::from_raw_parts(ip_header as *const _ as *const u16, count)\n    };\n\n    for &word in u16_slice {\n        sum += word as u32;\n    }\n\n    sum = (sum & 0xffff) + (sum >> 16);\n    !sum as u16\n}\n\npub struct xdp_md<'a> {\n    pub data_slice: &'a mut [c_uchar],\n    kptr: &'static mut xdp_buff,\n}\n\n// Define accessors of program-accessible fields\nimpl xdp_md<'_> {\n    #[inline(always)]\n    pub fn data_length(&self) -> usize {\n        self.data_slice.len()\n    }\n\n    #[inline(always)]\n    pub fn data_meta(&self) -> usize {\n        self.kptr.data_meta as usize\n    }\n\n    #[inline(always)]\n    pub fn ingress_ifindex(&self) -> u32 {\n        unsafe { (*(*self.kptr.rxq).dev).ifindex as u32 }\n    }\n\n    #[inline(always)]\n    pub fn rx_qeueu_index(&self) -> u32 {\n        unsafe { (*self.kptr.rxq).queue_index }\n    }\n\n    #[inline(always)]\n    pub fn egress_ifindex(&self) -> u32 {\n        // TODO: https://elixir.bootlin.com/linux/v5.15.123/source/net/core/filter.c#L8271\n        // egress_ifindex is valid only for BPF_XDP_DEVMAP option\n        0\n    }\n}\n\n#[repr(C)]\npub struct xdp {\n    _placeholder: PhantomData<()>,\n}\n\nimpl xdp {\n    crate::base_helper::base_helper_defs!();\n\n    pub const unsafe fn new() -> xdp {\n        Self {\n            _placeholder: PhantomData,\n        }\n    }\n\n    // Now returns a mutable ref, but since every reg is private the user prog\n    // cannot change reg contents. The user should not be able to directly\n    // assign this reference a new value either, given that they will not able\n    // to create another instance of pt_regs (private fields, no pub ctor)\n    #[inline(always)]\n    pub unsafe fn convert_ctx(&self, ctx: *mut ()) -> xdp_md<'_> {\n        let kptr = unsafe { &mut *(ctx as *mut xdp_buff) };\n\n        // NOTE: not support jumobo frame yet with non-linear xdp_buff\n        let data_length = kptr.data_end as usize - kptr.data as usize;\n\n        let data_slice = unsafe {\n            slice::from_raw_parts_mut(kptr.data as *mut c_uchar, data_length)\n        };\n\n        xdp_md { data_slice, kptr }\n    }\n\n    #[inline(always)]\n    pub fn tcp_header<'b>(\n        &self,\n        ctx: &'b mut xdp_md,\n    ) -> AlignedMut<'b, tcphdr> {\n        // NOTE: this assumes packet has ethhdr and iphdr\n        let begin = mem::size_of::<ethhdr>() + mem::size_of::<iphdr>();\n        let end = mem::size_of::<tcphdr>() + begin;\n\n        convert_slice_to_struct_mut::<tcphdr>(&mut ctx.data_slice[begin..end])\n    }\n\n    #[inline(always)]\n    pub fn udp_header<'b>(\n        &self,\n        ctx: &'b mut xdp_md,\n    ) -> AlignedMut<'b, udphdr> {\n        // NOTE: this assumes packet has ethhdr and iphdr\n        let begin = mem::size_of::<ethhdr>() + mem::size_of::<iphdr>();\n        let end = mem::size_of::<udphdr>() + begin;\n\n        convert_slice_to_struct_mut::<udphdr>(&mut ctx.data_slice[begin..end])\n    }\n\n    #[inline(always)]\n    pub fn ip_header<'b>(&self, ctx: &'b mut xdp_md) -> AlignedMut<'b, iphdr> {\n        // NOTE: this assumes packet has ethhdr\n        let begin = mem::size_of::<ethhdr>();\n        let end = mem::size_of::<iphdr>() + begin;\n\n        convert_slice_to_struct_mut::<iphdr>(&mut ctx.data_slice[begin..end])\n    }\n\n    #[inline(always)]\n    pub fn eth_header<'b>(\n        &self,\n        ctx: &'b mut xdp_md,\n    ) -> AlignedMut<'b, ethhdr> {\n        convert_slice_to_struct_mut::<ethhdr>(\n            &mut ctx.data_slice[0..mem::size_of::<ethhdr>()],\n        )\n    }\n\n    // FIX: update based on xdp_md to convert to xdp_buff\n    // pub fn bpf_xdp_adjust_head(&self, xdp: &mut xdp_buff, offset: i32) -> i32\n    // {     unsafe { ffi::bpf_xdp_adjust_head(xdp, offset) }\n    // }\n\n    // WARN: this function is unsafe\n    #[inline(always)]\n    pub fn bpf_xdp_adjust_tail(&self, ctx: &mut xdp_md, offset: i32) -> Result {\n        let ret = termination_check!(unsafe {\n            ffi::bpf_xdp_adjust_tail(ctx.kptr, offset)\n        });\n        if ret != 0 {\n            return Err(ret);\n        }\n\n        // Update xdp_md fields\n        let data_length = ctx.kptr.data_end as usize - ctx.kptr.data as usize;\n\n        ctx.data_slice = unsafe {\n            slice::from_raw_parts_mut(\n                ctx.kptr.data as *mut c_uchar,\n                data_length,\n            )\n        };\n\n        Ok(0)\n    }\n}\n"
  },
  {
    "path": "rex-macros/.gitignore",
    "content": "# Generated by Cargo\n# will have compiled files and executables\ndebug/\ntarget/\n\n# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries\n# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html\nCargo.lock\n\n# These are backup files generated by rustfmt\n**/*.rs.bk\n\n# MSVC Windows builds of rustc generate these, which store debugging information\n*.pdb\n"
  },
  {
    "path": "rex-macros/Cargo.toml",
    "content": "[package]\nname = \"rex-macros\"\nversion = \"0.2.0\"\nrepository.workspace = true\nedition.workspace = true\nauthors.workspace = true\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[lib]\nproc-macro = true\n\n[dependencies]\nsyn = { workspace = true }\nquote = { workspace = true }\nproc-macro-error = { workspace = true }\nproc-macro2 = { workspace = true }\n\n"
  },
  {
    "path": "rex-macros/src/args.rs",
    "content": "use std::collections::HashMap;\n\nuse proc_macro2::TokenStream;\nuse proc_macro_error::abort;\nuse syn::spanned::Spanned;\nuse syn::{parse_str, Expr, ExprAssign, Lit, LitStr, Result};\n\nmacro_rules! pop_string_args {\n    ($self:expr, $key:expr) => {\n        $self.get($key).map(|v| v.value())\n    };\n}\n\npub(crate) fn parse_string_args(\n    input: TokenStream,\n) -> Result<HashMap<String, LitStr>> {\n    let parsed: syn::ExprArray = parse_str(&format!(\"[{input}]\"))?;\n    let mut map = HashMap::new();\n\n    // Iterate over the expressions and extract key-value pairs\n    let parse_and_insert = |expr| {\n        let Expr::Assign(ExprAssign { left, right, .. }) = expr else {\n            return;\n        };\n        let Expr::Path(path) = *left else { return };\n        let Some(ident) = path.path.get_ident() else {\n            return;\n        };\n\n        let key = ident.to_string();\n        let value = match *right {\n            Expr::Lit(syn::ExprLit {\n                lit: Lit::Str(lit_str),\n                ..\n            }) => lit_str,\n            _ => {\n                abort!(input.span(), \"Macro processing failed, please follow the syntax `key` = `value`\");\n            }\n        };\n        map.insert(key, value);\n    };\n\n    parsed.elems.into_iter().for_each(parse_and_insert);\n\n    // println!(\"{:?}\", map);\n    Ok(map)\n}\n"
  },
  {
    "path": "rex-macros/src/kprobe.rs",
    "content": "use std::fmt;\n\nuse proc_macro2::TokenStream;\nuse quote::{format_ident, quote};\nuse syn::{parse2, ItemFn, Result};\n\nuse crate::args::parse_string_args;\n\n#[allow(dead_code)]\npub enum KprobeFlavor {\n    Kprobe,\n    Kretprobe,\n    Uprobe,\n    Uretprobe,\n}\n\nimpl fmt::Display for KprobeFlavor {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        match self {\n            KprobeFlavor::Kprobe => write!(f, \"kprobe\"),\n            KprobeFlavor::Kretprobe => write!(f, \"kretprobe\"),\n            KprobeFlavor::Uprobe => write!(f, \"uprobe\"),\n            KprobeFlavor::Uretprobe => write!(f, \"uretprobe\"),\n        }\n    }\n}\n\npub(crate) struct KProbe {\n    function: Option<String>,\n    item: ItemFn,\n}\n\nimpl KProbe {\n    // parse the argument of function\n    pub(crate) fn parse(\n        attrs: TokenStream,\n        item: TokenStream,\n    ) -> Result<KProbe> {\n        let item: ItemFn = parse2(item)?;\n        let args = parse_string_args(attrs)?;\n\n        let function = pop_string_args!(args, \"function\");\n\n        Ok(KProbe { function, item })\n    }\n\n    pub(crate) fn expand(&self, flavor: KprobeFlavor) -> Result<TokenStream> {\n        let fn_name = self.item.sig.ident.clone();\n        let item = &self.item;\n        let function_name = format!(\"{fn_name}\");\n        let prog_ident =\n            format_ident!(\"PROG_{}\", fn_name.to_string().to_uppercase());\n\n        let attached_function = if self.function.is_some() {\n            format!(\"rex/{}/{}\", flavor, self.function.as_ref().unwrap())\n        } else {\n            format!(\"rex/{flavor}\")\n        };\n\n        let entry_name = format_ident!(\"__rex_entry_{}\", fn_name);\n\n        let function_body_tokens = quote! {\n            #[inline(always)]\n            #item\n\n            #[used]\n            static #prog_ident: kprobe = unsafe { kprobe::new() };\n\n            #[unsafe(export_name = #function_name)]\n            #[unsafe(link_section = #attached_function)]\n            extern \"C\" fn #entry_name(ctx: *mut ()) -> u32 {\n                let newctx = unsafe { #prog_ident.convert_ctx(ctx) };\n                #fn_name(&#prog_ident, newctx).unwrap_or_else(|e| e) as u32\n            }\n        };\n\n        Ok(function_body_tokens)\n    }\n}\n"
  },
  {
    "path": "rex-macros/src/lib.rs",
    "content": "#[macro_use]\npub(crate) mod args;\nmod kprobe;\nmod perf_event;\nmod tc;\nmod tracepoint;\nmod xdp;\n\nuse std::borrow::Cow;\n\nuse kprobe::{KProbe, KprobeFlavor};\nuse perf_event::PerfEvent;\nuse proc_macro::TokenStream;\nuse proc_macro_error::{abort, proc_macro_error};\nuse quote::quote;\nuse syn::ItemStatic;\nuse tc::SchedCls;\nuse tracepoint::TracePoint;\nuse xdp::Xdp;\n\n#[proc_macro_error]\n#[proc_macro_attribute]\npub fn rex_xdp(attrs: TokenStream, item: TokenStream) -> TokenStream {\n    match Xdp::parse(attrs.into(), item.into()) {\n        Ok(prog) => prog\n            .expand()\n            .unwrap_or_else(|err| abort!(err.span(), \"{}\", err))\n            .into(),\n        Err(err) => abort!(err.span(), \"{}\", err),\n    }\n}\n\n#[proc_macro_error]\n#[proc_macro_attribute]\npub fn rex_tc(attrs: TokenStream, item: TokenStream) -> TokenStream {\n    match SchedCls::parse(attrs.into(), item.into()) {\n        Ok(prog) => prog\n            .expand()\n            .unwrap_or_else(|err| abort!(err.span(), \"{}\", err))\n            .into(),\n        Err(err) => abort!(err.span(), \"{}\", err),\n    }\n}\n\n#[proc_macro_error]\n#[proc_macro_attribute]\npub fn rex_kprobe(attrs: TokenStream, item: TokenStream) -> TokenStream {\n    match KProbe::parse(attrs.into(), item.into()) {\n        Ok(prog) => prog\n            .expand(KprobeFlavor::Kprobe)\n            .unwrap_or_else(|err| abort!(err.span(), \"{}\", err))\n            .into(),\n        Err(err) => abort!(err.span(), \"{}\", err),\n    }\n}\n\n#[proc_macro_error]\n#[proc_macro_attribute]\npub fn rex_uprobe(attrs: TokenStream, item: TokenStream) -> TokenStream {\n    match KProbe::parse(attrs.into(), item.into()) {\n        Ok(prog) => prog\n            .expand(KprobeFlavor::Uprobe)\n            .unwrap_or_else(|err| abort!(err.span(), \"{}\", err))\n            .into(),\n        Err(err) => abort!(err.span(), \"{}\", err),\n    }\n}\n\n#[proc_macro_error]\n#[proc_macro_attribute]\npub fn rex_tracepoint(attrs: TokenStream, item: TokenStream) -> TokenStream {\n    match TracePoint::parse(attrs.into(), item.into()) {\n        Ok(prog) => prog\n            .expand()\n            .unwrap_or_else(|err| abort!(err.span(), \"{}\", err))\n            .into(),\n        Err(err) => abort!(err.span(), \"{}\", err),\n    }\n}\n\n#[proc_macro_error]\n#[proc_macro_attribute]\npub fn rex_perf_event(attrs: TokenStream, item: TokenStream) -> TokenStream {\n    match PerfEvent::parse(attrs.into(), item.into()) {\n        Ok(prog) => prog\n            .expand()\n            .unwrap_or_else(|err| abort!(err.span(), \"{}\", err))\n            .into(),\n        Err(err) => abort!(err.span(), \"{}\", err),\n    }\n}\n\n/// Ref: <https://github.com/aya-rs/aya/blob/1cf3d3c222bda0351ee6a2bacf9cee5349556764/aya-ebpf-macros/src/lib.rs#L53>\n#[proc_macro_attribute]\npub fn rex_map(_: TokenStream, item: TokenStream) -> TokenStream {\n    let item: ItemStatic = syn::parse(item).unwrap();\n    let name = item.ident.to_string();\n    let section_name: Cow<'_, _> = \".maps\".to_string().into();\n    (quote! {\n        #[unsafe(link_section = #section_name)]\n        #[unsafe(export_name = #name)]\n        #[allow(non_upper_case_globals)]\n        #item\n    })\n    .into()\n}\n"
  },
  {
    "path": "rex-macros/src/perf_event.rs",
    "content": "use proc_macro2::TokenStream;\nuse quote::{format_ident, quote};\nuse syn::{ItemFn, Result};\n\npub(crate) struct PerfEvent {\n    item: ItemFn,\n}\n\nimpl PerfEvent {\n    // parse the argument of function\n    pub(crate) fn parse(\n        _: TokenStream,\n        item: TokenStream,\n    ) -> Result<PerfEvent> {\n        let item = syn::parse2(item)?;\n        Ok(PerfEvent { item })\n    }\n\n    pub(crate) fn expand(&self) -> Result<TokenStream> {\n        // TODO: section may update in the future\n        let fn_name = self.item.sig.ident.clone();\n        let item = &self.item;\n        let function_name = format!(\"{fn_name}\");\n        let prog_ident =\n            format_ident!(\"PROG_{}\", fn_name.to_string().to_uppercase());\n\n        let entry_name = format_ident!(\"__rex_entry_{}\", fn_name);\n\n        let function_body_tokens = quote! {\n            #[inline(always)]\n            #item\n\n            #[used]\n            static #prog_ident: perf_event = unsafe { perf_event::new() };\n\n            #[unsafe(export_name = #function_name)]\n            #[unsafe(link_section = \"rex/perf_event\")]\n            extern \"C\" fn #entry_name(ctx: *mut ()) -> u32 {\n                let newctx = unsafe { #prog_ident.convert_ctx(ctx) };\n                #fn_name(&#prog_ident, newctx).unwrap_or_else(|e| e) as u32\n            }\n        };\n        Ok(function_body_tokens)\n    }\n}\n"
  },
  {
    "path": "rex-macros/src/tc.rs",
    "content": "use proc_macro2::TokenStream;\nuse quote::{format_ident, quote};\nuse syn::{ItemFn, Result};\n\npub(crate) struct SchedCls {\n    item: ItemFn,\n}\n\nimpl SchedCls {\n    // parse the argument of function\n    pub(crate) fn parse(_: TokenStream, item: TokenStream) -> Result<SchedCls> {\n        let item = syn::parse2(item)?;\n        Ok(SchedCls { item })\n    }\n\n    // expand the function into two function with original function\n    //     #[entry_link(inner_unikernel/tc)]\n    // static PROG2: sched_cls = sched_cls::new(\n    //     xdp_tx_filter,\n    //     \"xdp_tx_filter\",\n    //     BPF_PROG_TYPE_SCHED_CLS as u64,\n    // );\n    pub(crate) fn expand(&self) -> Result<TokenStream> {\n        // TODO: section may update in the future\n        let fn_name = self.item.sig.ident.clone();\n        let item = &self.item;\n        let function_name = format!(\"{fn_name}\");\n        let prog_ident =\n            format_ident!(\"PROG_{}\", fn_name.to_string().to_uppercase());\n\n        let entry_name = format_ident!(\"__rex_entry_{}\", fn_name);\n\n        let function_body_tokens = quote! {\n            #[inline(always)]\n            #item\n\n            #[used]\n            static #prog_ident: sched_cls = unsafe { sched_cls::new() };\n\n            #[unsafe(export_name = #function_name)]\n            #[unsafe(link_section = \"rex/tc\")]\n            extern \"C\" fn #entry_name(ctx: *mut ()) -> u32 {\n                let mut newctx = unsafe { #prog_ident.convert_ctx(ctx) };\n                // return TC_ACT_OK if error\n                #fn_name(&#prog_ident, &mut newctx).unwrap_or_else(|e| e) as u32\n            }\n        };\n        Ok(function_body_tokens)\n    }\n}\n"
  },
  {
    "path": "rex-macros/src/tracepoint.rs",
    "content": "use proc_macro2::TokenStream;\nuse proc_macro_error::abort_call_site;\nuse quote::{format_ident, quote, ToTokens};\nuse syn::{parse2, FnArg, Ident, ItemFn, Result, Type};\n\npub(crate) struct TracePoint {\n    item: ItemFn,\n}\n\nimpl TracePoint {\n    // parse the argument of function\n    pub(crate) fn parse(\n        _attrs: TokenStream,\n        item: TokenStream,\n    ) -> Result<TracePoint> {\n        let item: ItemFn = parse2(item)?;\n        Ok(TracePoint { item })\n    }\n\n    pub(crate) fn expand(&self) -> Result<TokenStream> {\n        let fn_name = self.item.sig.ident.clone();\n\n        // get context type\n        let FnArg::Typed(context_arg) =\n            self.item.sig.inputs.last().unwrap().clone()\n        else {\n            abort_call_site!(\"Program needs non-self arguments\");\n        };\n        let Type::Reference(context_type_ref) = *context_arg.ty else {\n            abort_call_site!(\"Context type needs to be behind a reference\");\n        };\n        let context_type = match *context_type_ref.elem.clone() {\n            Type::Verbatim(t) => parse2(t).unwrap(),\n            Type::Path(p) => p.path.segments.last().unwrap().clone().ident,\n            _ => {\n                abort_call_site!(\"Tracepoint context needs to be a literal type or a path to such\")\n            }\n        };\n        let full_context_type: Ident = match *context_type_ref.elem {\n            Type::Verbatim(t) => parse2(t).unwrap(),\n            Type::Path(p) => parse2(p.to_token_stream()).unwrap(),\n            _ => unreachable!(),\n        };\n\n        // other tracepoint pieces\n        let item = &self.item;\n        let function_name = format!(\"{fn_name}\");\n        let prog_ident =\n            format_ident!(\"PROG_{}\", fn_name.to_string().to_uppercase());\n\n        let hook_point_name = match context_type.to_string().as_str() {\n            \"SyscallsEnterOpenCtx\" => \"syscalls/sys_enter_open\",\n            \"SyscallsEnterOpenatCtx\" => \"syscalls/sys_enter_openat\",\n            \"SyscallsExitOpenCtx\" => \"syscalls/sys_exit_open\",\n            \"SyscallsExitOpenatCtx\" => \"syscalls/sys_exit_openat\",\n            \"SyscallsEnterDupCtx\" => \"syscalls/sys_enter_dup\",\n            \"RawSyscallsEnterCtx\" => \"raw_syscalls/sys_enter\",\n            \"RawSyscallsExitCtx\" => \"raw_syscalls/sys_exit\",\n            _ => abort_call_site!(\"Please provide a valid context type. If your needed context isn't supported consider opening a PR!\"),\n        };\n        let attached_name = format!(\"rex/tracepoint/{hook_point_name}\");\n\n        let entry_name = format_ident!(\"__rex_entry_{}\", fn_name);\n\n        let function_body_tokens = quote! {\n            #[inline(always)]\n            #item\n\n            #[used]\n            static #prog_ident: tracepoint<#full_context_type> =\n               unsafe { tracepoint::new() };\n\n            #[unsafe(export_name = #function_name)]\n            #[unsafe(link_section = #attached_name)]\n            extern \"C\" fn #entry_name(ctx: *mut ()) -> u32 {\n                let newctx = unsafe { #prog_ident.convert_ctx(ctx) };\n                #fn_name(&#prog_ident, newctx).unwrap_or_else(|e| e) as u32\n            }\n        };\n\n        Ok(function_body_tokens)\n    }\n}\n"
  },
  {
    "path": "rex-macros/src/xdp.rs",
    "content": "use proc_macro2::TokenStream;\nuse quote::{format_ident, quote};\nuse syn::{ItemFn, Result};\n\npub(crate) struct Xdp {\n    item: ItemFn,\n}\n\nimpl Xdp {\n    // parse the argument of function\n    pub(crate) fn parse(_: TokenStream, item: TokenStream) -> Result<Xdp> {\n        let item = syn::parse2(item)?;\n        Ok(Xdp { item })\n    }\n\n    // expand the function into two function with original function\n    // #[entry_link(inner_unikernel/xdp)]\n    // static PROG1: xdp =\n    // xdp::new(xdp_rx_filter_fn, \"xdp_rx_filter\", BPF_PROG_TYPE_XDP as u64);\n    pub(crate) fn expand(&self) -> Result<TokenStream> {\n        // TODO: section may update in the future\n        let fn_name = self.item.sig.ident.clone();\n        let item = &self.item;\n        let function_name = format!(\"{fn_name}\");\n        let prog_ident =\n            format_ident!(\"PROG_{}\", fn_name.to_string().to_uppercase());\n\n        let entry_name = format_ident!(\"__rex_entry_{}\", fn_name);\n\n        let function_body_tokens = quote! {\n            #[inline(always)]\n            #item\n\n            #[used]\n            static #prog_ident: xdp = unsafe { xdp::new() };\n\n            #[unsafe(export_name = #function_name)]\n            #[unsafe(link_section = \"rex/xdp\")]\n            extern \"C\" fn #entry_name(ctx: *mut ()) -> u32 {\n                let mut newctx = unsafe { #prog_ident.convert_ctx(ctx) };\n                // Return XDP_PASS if Err, i.e. discard event\n                #fn_name(&#prog_ident, &mut newctx).unwrap_or_else(|e| e) as u32\n            }\n        };\n        Ok(function_body_tokens)\n    }\n}\n"
  },
  {
    "path": "rex-native.ini",
    "content": "[binaries]\nc = 'clang'\nc_ld = 'mold'\ncpp = 'clang++'\ncpp_ld = 'mold'\nar = 'llvm-ar'\n\n"
  },
  {
    "path": "rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/.clang-format",
    "content": "# SPDX-License-Identifier: GPL-2.0\n#\n# clang-format configuration file. Intended for clang-format >= 11.\n#\n# For more information, see:\n#\n#   Documentation/dev-tools/clang-format.rst\n#   https://clang.llvm.org/docs/ClangFormat.html\n#   https://clang.llvm.org/docs/ClangFormatStyleOptions.html\n#\n---\nAccessModifierOffset: -4\nAlignAfterOpenBracket: Align\nAlignConsecutiveAssignments: false\nAlignConsecutiveDeclarations: false\nAlignEscapedNewlines: Left\nAlignOperands: true\nAlignTrailingComments: false\nAllowAllParametersOfDeclarationOnNextLine: false\nAllowShortBlocksOnASingleLine: false\nAllowShortCaseLabelsOnASingleLine: false\nAllowShortFunctionsOnASingleLine: None\nAllowShortIfStatementsOnASingleLine: false\nAllowShortLoopsOnASingleLine: false\nAlwaysBreakAfterDefinitionReturnType: None\nAlwaysBreakAfterReturnType: None\nAlwaysBreakBeforeMultilineStrings: false\nAlwaysBreakTemplateDeclarations: false\nBinPackArguments: true\nBinPackParameters: true\nBraceWrapping:\n  AfterClass: false\n  AfterControlStatement: false\n  AfterEnum: false\n  AfterFunction: true\n  AfterNamespace: true\n  AfterObjCDeclaration: false\n  AfterStruct: false\n  AfterUnion: false\n  AfterExternBlock: false\n  BeforeCatch: false\n  BeforeElse: false\n  IndentBraces: false\n  SplitEmptyFunction: true\n  SplitEmptyRecord: true\n  SplitEmptyNamespace: true\nBreakBeforeBinaryOperators: None\nBreakBeforeBraces: Custom\nBreakBeforeInheritanceComma: false\nBreakBeforeTernaryOperators: false\nBreakConstructorInitializersBeforeComma: false\nBreakConstructorInitializers: BeforeComma\nBreakAfterJavaFieldAnnotations: false\nBreakStringLiterals: false\nColumnLimit: 80\nCommentPragmas: '^ IWYU pragma:'\nCompactNamespaces: false\nConstructorInitializerAllOnOneLineOrOnePerLine: false\nConstructorInitializerIndentWidth: 8\nContinuationIndentWidth: 8\nCpp11BracedListStyle: false\nDerivePointerAlignment: false\nDisableFormat: false\nExperimentalAutoDetectBinPacking: false\nFixNamespaceComments: false\n\n# Taken from:\n#   git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ tools/ \\\n#   | sed \"s,^#define \\([^[:space:]]*for_each[^[:space:]]*\\)(.*$,  - '\\1',\" \\\n#   | LC_ALL=C sort -u\nForEachMacros:\n  - '__ata_qc_for_each'\n  - '__bio_for_each_bvec'\n  - '__bio_for_each_segment'\n  - '__evlist__for_each_entry'\n  - '__evlist__for_each_entry_continue'\n  - '__evlist__for_each_entry_from'\n  - '__evlist__for_each_entry_reverse'\n  - '__evlist__for_each_entry_safe'\n  - '__for_each_mem_range'\n  - '__for_each_mem_range_rev'\n  - '__for_each_thread'\n  - '__hlist_for_each_rcu'\n  - '__map__for_each_symbol_by_name'\n  - '__pci_bus_for_each_res0'\n  - '__pci_bus_for_each_res1'\n  - '__pci_dev_for_each_res0'\n  - '__pci_dev_for_each_res1'\n  - '__perf_evlist__for_each_entry'\n  - '__perf_evlist__for_each_entry_reverse'\n  - '__perf_evlist__for_each_entry_safe'\n  - '__rq_for_each_bio'\n  - '__shost_for_each_device'\n  - '__sym_for_each'\n  - 'apei_estatus_for_each_section'\n  - 'ata_for_each_dev'\n  - 'ata_for_each_link'\n  - 'ata_qc_for_each'\n  - 'ata_qc_for_each_raw'\n  - 'ata_qc_for_each_with_internal'\n  - 'ax25_for_each'\n  - 'ax25_uid_for_each'\n  - 'bio_for_each_bvec'\n  - 'bio_for_each_bvec_all'\n  - 'bio_for_each_folio_all'\n  - 'bio_for_each_integrity_vec'\n  - 'bio_for_each_segment'\n  - 'bio_for_each_segment_all'\n  - 'bio_list_for_each'\n  - 'bip_for_each_vec'\n  - 'bond_for_each_slave'\n  - 'bond_for_each_slave_rcu'\n  - 'bpf_for_each'\n  - 'bpf_for_each_reg_in_vstate'\n  - 'bpf_for_each_reg_in_vstate_mask'\n  - 'bpf_for_each_spilled_reg'\n  - 'bpf_object__for_each_map'\n  - 'bpf_object__for_each_program'\n  - 'btree_for_each_safe128'\n  - 'btree_for_each_safe32'\n  - 'btree_for_each_safe64'\n  - 'btree_for_each_safel'\n  - 'card_for_each_dev'\n  - 'cgroup_taskset_for_each'\n  - 'cgroup_taskset_for_each_leader'\n  - 'cpu_aggr_map__for_each_idx'\n  - 'cpufreq_for_each_efficient_entry_idx'\n  - 'cpufreq_for_each_entry'\n  - 'cpufreq_for_each_entry_idx'\n  - 'cpufreq_for_each_valid_entry'\n  - 'cpufreq_for_each_valid_entry_idx'\n  - 'css_for_each_child'\n  - 'css_for_each_descendant_post'\n  - 'css_for_each_descendant_pre'\n  - 'damon_for_each_region'\n  - 'damon_for_each_region_from'\n  - 'damon_for_each_region_safe'\n  - 'damon_for_each_scheme'\n  - 'damon_for_each_scheme_safe'\n  - 'damon_for_each_target'\n  - 'damon_for_each_target_safe'\n  - 'damos_for_each_filter'\n  - 'damos_for_each_filter_safe'\n  - 'data__for_each_file'\n  - 'data__for_each_file_new'\n  - 'data__for_each_file_start'\n  - 'device_for_each_child_node'\n  - 'displayid_iter_for_each'\n  - 'dma_fence_array_for_each'\n  - 'dma_fence_chain_for_each'\n  - 'dma_fence_unwrap_for_each'\n  - 'dma_resv_for_each_fence'\n  - 'dma_resv_for_each_fence_unlocked'\n  - 'do_for_each_ftrace_op'\n  - 'drm_atomic_crtc_for_each_plane'\n  - 'drm_atomic_crtc_state_for_each_plane'\n  - 'drm_atomic_crtc_state_for_each_plane_state'\n  - 'drm_atomic_for_each_plane_damage'\n  - 'drm_client_for_each_connector_iter'\n  - 'drm_client_for_each_modeset'\n  - 'drm_connector_for_each_possible_encoder'\n  - 'drm_exec_for_each_locked_object'\n  - 'drm_exec_for_each_locked_object_reverse'\n  - 'drm_for_each_bridge_in_chain'\n  - 'drm_for_each_connector_iter'\n  - 'drm_for_each_crtc'\n  - 'drm_for_each_crtc_reverse'\n  - 'drm_for_each_encoder'\n  - 'drm_for_each_encoder_mask'\n  - 'drm_for_each_fb'\n  - 'drm_for_each_legacy_plane'\n  - 'drm_for_each_plane'\n  - 'drm_for_each_plane_mask'\n  - 'drm_for_each_privobj'\n  - 'drm_gem_for_each_gpuva'\n  - 'drm_gem_for_each_gpuva_safe'\n  - 'drm_gpuva_for_each_op'\n  - 'drm_gpuva_for_each_op_from_reverse'\n  - 'drm_gpuva_for_each_op_safe'\n  - 'drm_gpuvm_for_each_va'\n  - 'drm_gpuvm_for_each_va_range'\n  - 'drm_gpuvm_for_each_va_range_safe'\n  - 'drm_gpuvm_for_each_va_safe'\n  - 'drm_mm_for_each_hole'\n  - 'drm_mm_for_each_node'\n  - 'drm_mm_for_each_node_in_range'\n  - 'drm_mm_for_each_node_safe'\n  - 'dsa_switch_for_each_available_port'\n  - 'dsa_switch_for_each_cpu_port'\n  - 'dsa_switch_for_each_cpu_port_continue_reverse'\n  - 'dsa_switch_for_each_port'\n  - 'dsa_switch_for_each_port_continue_reverse'\n  - 'dsa_switch_for_each_port_safe'\n  - 'dsa_switch_for_each_user_port'\n  - 'dsa_tree_for_each_cpu_port'\n  - 'dsa_tree_for_each_user_port'\n  - 'dsa_tree_for_each_user_port_continue_reverse'\n  - 'dso__for_each_symbol'\n  - 'dsos__for_each_with_build_id'\n  - 'elf_hash_for_each_possible'\n  - 'elf_symtab__for_each_symbol'\n  - 'evlist__for_each_cpu'\n  - 'evlist__for_each_entry'\n  - 'evlist__for_each_entry_continue'\n  - 'evlist__for_each_entry_from'\n  - 'evlist__for_each_entry_reverse'\n  - 'evlist__for_each_entry_safe'\n  - 'flow_action_for_each'\n  - 'for_each_acpi_consumer_dev'\n  - 'for_each_acpi_dev_match'\n  - 'for_each_active_dev_scope'\n  - 'for_each_active_drhd_unit'\n  - 'for_each_active_iommu'\n  - 'for_each_active_route'\n  - 'for_each_aggr_pgid'\n  - 'for_each_and_bit'\n  - 'for_each_andnot_bit'\n  - 'for_each_available_child_of_node'\n  - 'for_each_bench'\n  - 'for_each_bio'\n  - 'for_each_board_func_rsrc'\n  - 'for_each_btf_ext_rec'\n  - 'for_each_btf_ext_sec'\n  - 'for_each_bvec'\n  - 'for_each_card_auxs'\n  - 'for_each_card_auxs_safe'\n  - 'for_each_card_components'\n  - 'for_each_card_dapms'\n  - 'for_each_card_pre_auxs'\n  - 'for_each_card_prelinks'\n  - 'for_each_card_rtds'\n  - 'for_each_card_rtds_safe'\n  - 'for_each_card_widgets'\n  - 'for_each_card_widgets_safe'\n  - 'for_each_cgroup_storage_type'\n  - 'for_each_child_of_node'\n  - 'for_each_clear_bit'\n  - 'for_each_clear_bit_from'\n  - 'for_each_clear_bitrange'\n  - 'for_each_clear_bitrange_from'\n  - 'for_each_cmd'\n  - 'for_each_cmsghdr'\n  - 'for_each_collection'\n  - 'for_each_comp_order'\n  - 'for_each_compatible_node'\n  - 'for_each_component_dais'\n  - 'for_each_component_dais_safe'\n  - 'for_each_conduit'\n  - 'for_each_console'\n  - 'for_each_console_srcu'\n  - 'for_each_cpu'\n  - 'for_each_cpu_and'\n  - 'for_each_cpu_andnot'\n  - 'for_each_cpu_or'\n  - 'for_each_cpu_wrap'\n  - 'for_each_dapm_widgets'\n  - 'for_each_dedup_cand'\n  - 'for_each_dev_addr'\n  - 'for_each_dev_scope'\n  - 'for_each_dma_cap_mask'\n  - 'for_each_dpcm_be'\n  - 'for_each_dpcm_be_rollback'\n  - 'for_each_dpcm_be_safe'\n  - 'for_each_dpcm_fe'\n  - 'for_each_drhd_unit'\n  - 'for_each_dss_dev'\n  - 'for_each_efi_memory_desc'\n  - 'for_each_efi_memory_desc_in_map'\n  - 'for_each_element'\n  - 'for_each_element_extid'\n  - 'for_each_element_id'\n  - 'for_each_endpoint_of_node'\n  - 'for_each_event'\n  - 'for_each_event_tps'\n  - 'for_each_evictable_lru'\n  - 'for_each_fib6_node_rt_rcu'\n  - 'for_each_fib6_walker_rt'\n  - 'for_each_free_mem_pfn_range_in_zone'\n  - 'for_each_free_mem_pfn_range_in_zone_from'\n  - 'for_each_free_mem_range'\n  - 'for_each_free_mem_range_reverse'\n  - 'for_each_func_rsrc'\n  - 'for_each_gpiochip_node'\n  - 'for_each_group_evsel'\n  - 'for_each_group_evsel_head'\n  - 'for_each_group_member'\n  - 'for_each_group_member_head'\n  - 'for_each_hstate'\n  - 'for_each_if'\n  - 'for_each_inject_fn'\n  - 'for_each_insn'\n  - 'for_each_insn_prefix'\n  - 'for_each_intid'\n  - 'for_each_iommu'\n  - 'for_each_ip_tunnel_rcu'\n  - 'for_each_irq_nr'\n  - 'for_each_lang'\n  - 'for_each_link_codecs'\n  - 'for_each_link_cpus'\n  - 'for_each_link_platforms'\n  - 'for_each_lru'\n  - 'for_each_matching_node'\n  - 'for_each_matching_node_and_match'\n  - 'for_each_media_entity_data_link'\n  - 'for_each_mem_pfn_range'\n  - 'for_each_mem_range'\n  - 'for_each_mem_range_rev'\n  - 'for_each_mem_region'\n  - 'for_each_member'\n  - 'for_each_memory'\n  - 'for_each_migratetype_order'\n  - 'for_each_missing_reg'\n  - 'for_each_mle_subelement'\n  - 'for_each_mod_mem_type'\n  - 'for_each_net'\n  - 'for_each_net_continue_reverse'\n  - 'for_each_net_rcu'\n  - 'for_each_netdev'\n  - 'for_each_netdev_continue'\n  - 'for_each_netdev_continue_rcu'\n  - 'for_each_netdev_continue_reverse'\n  - 'for_each_netdev_dump'\n  - 'for_each_netdev_feature'\n  - 'for_each_netdev_in_bond_rcu'\n  - 'for_each_netdev_rcu'\n  - 'for_each_netdev_reverse'\n  - 'for_each_netdev_safe'\n  - 'for_each_new_connector_in_state'\n  - 'for_each_new_crtc_in_state'\n  - 'for_each_new_mst_mgr_in_state'\n  - 'for_each_new_plane_in_state'\n  - 'for_each_new_plane_in_state_reverse'\n  - 'for_each_new_private_obj_in_state'\n  - 'for_each_new_reg'\n  - 'for_each_node'\n  - 'for_each_node_by_name'\n  - 'for_each_node_by_type'\n  - 'for_each_node_mask'\n  - 'for_each_node_state'\n  - 'for_each_node_with_cpus'\n  - 'for_each_node_with_property'\n  - 'for_each_nonreserved_multicast_dest_pgid'\n  - 'for_each_numa_hop_mask'\n  - 'for_each_of_allnodes'\n  - 'for_each_of_allnodes_from'\n  - 'for_each_of_cpu_node'\n  - 'for_each_of_pci_range'\n  - 'for_each_old_connector_in_state'\n  - 'for_each_old_crtc_in_state'\n  - 'for_each_old_mst_mgr_in_state'\n  - 'for_each_old_plane_in_state'\n  - 'for_each_old_private_obj_in_state'\n  - 'for_each_oldnew_connector_in_state'\n  - 'for_each_oldnew_crtc_in_state'\n  - 'for_each_oldnew_mst_mgr_in_state'\n  - 'for_each_oldnew_plane_in_state'\n  - 'for_each_oldnew_plane_in_state_reverse'\n  - 'for_each_oldnew_private_obj_in_state'\n  - 'for_each_online_cpu'\n  - 'for_each_online_node'\n  - 'for_each_online_pgdat'\n  - 'for_each_or_bit'\n  - 'for_each_path'\n  - 'for_each_pci_bridge'\n  - 'for_each_pci_dev'\n  - 'for_each_pcm_streams'\n  - 'for_each_physmem_range'\n  - 'for_each_populated_zone'\n  - 'for_each_possible_cpu'\n  - 'for_each_present_blessed_reg'\n  - 'for_each_present_cpu'\n  - 'for_each_prime_number'\n  - 'for_each_prime_number_from'\n  - 'for_each_probe_cache_entry'\n  - 'for_each_process'\n  - 'for_each_process_thread'\n  - 'for_each_prop_codec_conf'\n  - 'for_each_prop_dai_codec'\n  - 'for_each_prop_dai_cpu'\n  - 'for_each_prop_dlc_codecs'\n  - 'for_each_prop_dlc_cpus'\n  - 'for_each_prop_dlc_platforms'\n  - 'for_each_property_of_node'\n  - 'for_each_reg'\n  - 'for_each_reg_filtered'\n  - 'for_each_reloc'\n  - 'for_each_reloc_from'\n  - 'for_each_requested_gpio'\n  - 'for_each_requested_gpio_in_range'\n  - 'for_each_reserved_mem_range'\n  - 'for_each_reserved_mem_region'\n  - 'for_each_rtd_codec_dais'\n  - 'for_each_rtd_components'\n  - 'for_each_rtd_cpu_dais'\n  - 'for_each_rtd_dais'\n  - 'for_each_sband_iftype_data'\n  - 'for_each_script'\n  - 'for_each_sec'\n  - 'for_each_set_bit'\n  - 'for_each_set_bit_from'\n  - 'for_each_set_bit_wrap'\n  - 'for_each_set_bitrange'\n  - 'for_each_set_bitrange_from'\n  - 'for_each_set_clump8'\n  - 'for_each_sg'\n  - 'for_each_sg_dma_page'\n  - 'for_each_sg_page'\n  - 'for_each_sgtable_dma_page'\n  - 'for_each_sgtable_dma_sg'\n  - 'for_each_sgtable_page'\n  - 'for_each_sgtable_sg'\n  - 'for_each_sibling_event'\n  - 'for_each_sta_active_link'\n  - 'for_each_subelement'\n  - 'for_each_subelement_extid'\n  - 'for_each_subelement_id'\n  - 'for_each_sublist'\n  - 'for_each_subsystem'\n  - 'for_each_supported_activate_fn'\n  - 'for_each_supported_inject_fn'\n  - 'for_each_sym'\n  - 'for_each_test'\n  - 'for_each_thread'\n  - 'for_each_token'\n  - 'for_each_unicast_dest_pgid'\n  - 'for_each_valid_link'\n  - 'for_each_vif_active_link'\n  - 'for_each_vma'\n  - 'for_each_vma_range'\n  - 'for_each_vsi'\n  - 'for_each_wakeup_source'\n  - 'for_each_zone'\n  - 'for_each_zone_zonelist'\n  - 'for_each_zone_zonelist_nodemask'\n  - 'func_for_each_insn'\n  - 'fwnode_for_each_available_child_node'\n  - 'fwnode_for_each_child_node'\n  - 'fwnode_for_each_parent_node'\n  - 'fwnode_graph_for_each_endpoint'\n  - 'gadget_for_each_ep'\n  - 'genradix_for_each'\n  - 'genradix_for_each_from'\n  - 'genradix_for_each_reverse'\n  - 'hash_for_each'\n  - 'hash_for_each_possible'\n  - 'hash_for_each_possible_rcu'\n  - 'hash_for_each_possible_rcu_notrace'\n  - 'hash_for_each_possible_safe'\n  - 'hash_for_each_rcu'\n  - 'hash_for_each_safe'\n  - 'hashmap__for_each_entry'\n  - 'hashmap__for_each_entry_safe'\n  - 'hashmap__for_each_key_entry'\n  - 'hashmap__for_each_key_entry_safe'\n  - 'hctx_for_each_ctx'\n  - 'hists__for_each_format'\n  - 'hists__for_each_sort_list'\n  - 'hlist_bl_for_each_entry'\n  - 'hlist_bl_for_each_entry_rcu'\n  - 'hlist_bl_for_each_entry_safe'\n  - 'hlist_for_each'\n  - 'hlist_for_each_entry'\n  - 'hlist_for_each_entry_continue'\n  - 'hlist_for_each_entry_continue_rcu'\n  - 'hlist_for_each_entry_continue_rcu_bh'\n  - 'hlist_for_each_entry_from'\n  - 'hlist_for_each_entry_from_rcu'\n  - 'hlist_for_each_entry_rcu'\n  - 'hlist_for_each_entry_rcu_bh'\n  - 'hlist_for_each_entry_rcu_notrace'\n  - 'hlist_for_each_entry_safe'\n  - 'hlist_for_each_entry_srcu'\n  - 'hlist_for_each_safe'\n  - 'hlist_nulls_for_each_entry'\n  - 'hlist_nulls_for_each_entry_from'\n  - 'hlist_nulls_for_each_entry_rcu'\n  - 'hlist_nulls_for_each_entry_safe'\n  - 'i3c_bus_for_each_i2cdev'\n  - 'i3c_bus_for_each_i3cdev'\n  - 'idr_for_each_entry'\n  - 'idr_for_each_entry_continue'\n  - 'idr_for_each_entry_continue_ul'\n  - 'idr_for_each_entry_ul'\n  - 'in_dev_for_each_ifa_rcu'\n  - 'in_dev_for_each_ifa_rtnl'\n  - 'inet_bind_bucket_for_each'\n  - 'interval_tree_for_each_span'\n  - 'intlist__for_each_entry'\n  - 'intlist__for_each_entry_safe'\n  - 'kcore_copy__for_each_phdr'\n  - 'key_for_each'\n  - 'key_for_each_safe'\n  - 'klp_for_each_func'\n  - 'klp_for_each_func_safe'\n  - 'klp_for_each_func_static'\n  - 'klp_for_each_object'\n  - 'klp_for_each_object_safe'\n  - 'klp_for_each_object_static'\n  - 'kunit_suite_for_each_test_case'\n  - 'kvm_for_each_memslot'\n  - 'kvm_for_each_memslot_in_gfn_range'\n  - 'kvm_for_each_vcpu'\n  - 'libbpf_nla_for_each_attr'\n  - 'list_for_each'\n  - 'list_for_each_codec'\n  - 'list_for_each_codec_safe'\n  - 'list_for_each_continue'\n  - 'list_for_each_entry'\n  - 'list_for_each_entry_continue'\n  - 'list_for_each_entry_continue_rcu'\n  - 'list_for_each_entry_continue_reverse'\n  - 'list_for_each_entry_from'\n  - 'list_for_each_entry_from_rcu'\n  - 'list_for_each_entry_from_reverse'\n  - 'list_for_each_entry_lockless'\n  - 'list_for_each_entry_rcu'\n  - 'list_for_each_entry_reverse'\n  - 'list_for_each_entry_safe'\n  - 'list_for_each_entry_safe_continue'\n  - 'list_for_each_entry_safe_from'\n  - 'list_for_each_entry_safe_reverse'\n  - 'list_for_each_entry_srcu'\n  - 'list_for_each_from'\n  - 'list_for_each_prev'\n  - 'list_for_each_prev_safe'\n  - 'list_for_each_rcu'\n  - 'list_for_each_reverse'\n  - 'list_for_each_safe'\n  - 'llist_for_each'\n  - 'llist_for_each_entry'\n  - 'llist_for_each_entry_safe'\n  - 'llist_for_each_safe'\n  - 'lwq_for_each_safe'\n  - 'map__for_each_symbol'\n  - 'map__for_each_symbol_by_name'\n  - 'maps__for_each_entry'\n  - 'maps__for_each_entry_safe'\n  - 'mas_for_each'\n  - 'mci_for_each_dimm'\n  - 'media_device_for_each_entity'\n  - 'media_device_for_each_intf'\n  - 'media_device_for_each_link'\n  - 'media_device_for_each_pad'\n  - 'media_entity_for_each_pad'\n  - 'media_pipeline_for_each_entity'\n  - 'media_pipeline_for_each_pad'\n  - 'mlx5_lag_for_each_peer_mdev'\n  - 'msi_domain_for_each_desc'\n  - 'msi_for_each_desc'\n  - 'mt_for_each'\n  - 'nanddev_io_for_each_page'\n  - 'netdev_for_each_lower_dev'\n  - 'netdev_for_each_lower_private'\n  - 'netdev_for_each_lower_private_rcu'\n  - 'netdev_for_each_mc_addr'\n  - 'netdev_for_each_synced_mc_addr'\n  - 'netdev_for_each_synced_uc_addr'\n  - 'netdev_for_each_uc_addr'\n  - 'netdev_for_each_upper_dev_rcu'\n  - 'netdev_hw_addr_list_for_each'\n  - 'nft_rule_for_each_expr'\n  - 'nla_for_each_attr'\n  - 'nla_for_each_nested'\n  - 'nlmsg_for_each_attr'\n  - 'nlmsg_for_each_msg'\n  - 'nr_neigh_for_each'\n  - 'nr_neigh_for_each_safe'\n  - 'nr_node_for_each'\n  - 'nr_node_for_each_safe'\n  - 'of_for_each_phandle'\n  - 'of_property_for_each_string'\n  - 'of_property_for_each_u32'\n  - 'pci_bus_for_each_resource'\n  - 'pci_dev_for_each_resource'\n  - 'pcl_for_each_chunk'\n  - 'pcl_for_each_segment'\n  - 'pcm_for_each_format'\n  - 'perf_config_items__for_each_entry'\n  - 'perf_config_sections__for_each_entry'\n  - 'perf_config_set__for_each_entry'\n  - 'perf_cpu_map__for_each_cpu'\n  - 'perf_cpu_map__for_each_idx'\n  - 'perf_evlist__for_each_entry'\n  - 'perf_evlist__for_each_entry_reverse'\n  - 'perf_evlist__for_each_entry_safe'\n  - 'perf_evlist__for_each_evsel'\n  - 'perf_evlist__for_each_mmap'\n  - 'perf_hpp_list__for_each_format'\n  - 'perf_hpp_list__for_each_format_safe'\n  - 'perf_hpp_list__for_each_sort_list'\n  - 'perf_hpp_list__for_each_sort_list_safe'\n  - 'perf_tool_event__for_each_event'\n  - 'plist_for_each'\n  - 'plist_for_each_continue'\n  - 'plist_for_each_entry'\n  - 'plist_for_each_entry_continue'\n  - 'plist_for_each_entry_safe'\n  - 'plist_for_each_safe'\n  - 'pnp_for_each_card'\n  - 'pnp_for_each_dev'\n  - 'protocol_for_each_card'\n  - 'protocol_for_each_dev'\n  - 'queue_for_each_hw_ctx'\n  - 'radix_tree_for_each_slot'\n  - 'radix_tree_for_each_tagged'\n  - 'rb_for_each'\n  - 'rbtree_postorder_for_each_entry_safe'\n  - 'rdma_for_each_block'\n  - 'rdma_for_each_port'\n  - 'rdma_umem_for_each_dma_block'\n  - 'resort_rb__for_each_entry'\n  - 'resource_list_for_each_entry'\n  - 'resource_list_for_each_entry_safe'\n  - 'rhl_for_each_entry_rcu'\n  - 'rhl_for_each_rcu'\n  - 'rht_for_each'\n  - 'rht_for_each_entry'\n  - 'rht_for_each_entry_from'\n  - 'rht_for_each_entry_rcu'\n  - 'rht_for_each_entry_rcu_from'\n  - 'rht_for_each_entry_safe'\n  - 'rht_for_each_from'\n  - 'rht_for_each_rcu'\n  - 'rht_for_each_rcu_from'\n  - 'rq_for_each_bvec'\n  - 'rq_for_each_segment'\n  - 'rq_list_for_each'\n  - 'rq_list_for_each_safe'\n  - 'sample_read_group__for_each'\n  - 'scsi_for_each_prot_sg'\n  - 'scsi_for_each_sg'\n  - 'sctp_for_each_hentry'\n  - 'sctp_skb_for_each'\n  - 'sec_for_each_insn'\n  - 'sec_for_each_insn_continue'\n  - 'sec_for_each_insn_from'\n  - 'sec_for_each_sym'\n  - 'shdma_for_each_chan'\n  - 'shost_for_each_device'\n  - 'sk_for_each'\n  - 'sk_for_each_bound'\n  - 'sk_for_each_bound_bhash2'\n  - 'sk_for_each_entry_offset_rcu'\n  - 'sk_for_each_from'\n  - 'sk_for_each_rcu'\n  - 'sk_for_each_safe'\n  - 'sk_nulls_for_each'\n  - 'sk_nulls_for_each_from'\n  - 'sk_nulls_for_each_rcu'\n  - 'snd_array_for_each'\n  - 'snd_pcm_group_for_each_entry'\n  - 'snd_soc_dapm_widget_for_each_path'\n  - 'snd_soc_dapm_widget_for_each_path_safe'\n  - 'snd_soc_dapm_widget_for_each_sink_path'\n  - 'snd_soc_dapm_widget_for_each_source_path'\n  - 'strlist__for_each_entry'\n  - 'strlist__for_each_entry_safe'\n  - 'sym_for_each_insn'\n  - 'sym_for_each_insn_continue_reverse'\n  - 'symbols__for_each_entry'\n  - 'tb_property_for_each'\n  - 'tcf_act_for_each_action'\n  - 'tcf_exts_for_each_action'\n  - 'ttm_resource_manager_for_each_res'\n  - 'twsk_for_each_bound_bhash2'\n  - 'udp_portaddr_for_each_entry'\n  - 'udp_portaddr_for_each_entry_rcu'\n  - 'usb_hub_for_each_child'\n  - 'v4l2_device_for_each_subdev'\n  - 'v4l2_m2m_for_each_dst_buf'\n  - 'v4l2_m2m_for_each_dst_buf_safe'\n  - 'v4l2_m2m_for_each_src_buf'\n  - 'v4l2_m2m_for_each_src_buf_safe'\n  - 'virtio_device_for_each_vq'\n  - 'while_for_each_ftrace_op'\n  - 'xa_for_each'\n  - 'xa_for_each_marked'\n  - 'xa_for_each_range'\n  - 'xa_for_each_start'\n  - 'xas_for_each'\n  - 'xas_for_each_conflict'\n  - 'xas_for_each_marked'\n  - 'xbc_array_for_each_value'\n  - 'xbc_for_each_key_value'\n  - 'xbc_node_for_each_array_value'\n  - 'xbc_node_for_each_child'\n  - 'xbc_node_for_each_key_value'\n  - 'xbc_node_for_each_subkey'\n  - 'zorro_for_each_dev'\n\nIncludeBlocks: Preserve\nIncludeCategories:\n  - Regex: '.*'\n    Priority: 1\nIncludeIsMainRegex: '(Test)?$'\nIndentCaseLabels: false\nIndentGotoLabels: false\nIndentPPDirectives: None\nIndentWidth: 8\nIndentWrappedFunctionNames: false\nJavaScriptQuotes: Leave\nJavaScriptWrapImports: true\nKeepEmptyLinesAtTheStartOfBlocks: false\nMacroBlockBegin: ''\nMacroBlockEnd: ''\nMaxEmptyLinesToKeep: 1\nNamespaceIndentation: None\nObjCBinPackProtocolList: Auto\nObjCBlockIndentWidth: 8\nObjCSpaceAfterProperty: true\nObjCSpaceBeforeProtocolList: true\n\n# Taken from git's rules\nPenaltyBreakAssignment: 10\nPenaltyBreakBeforeFirstCallParameter: 30\nPenaltyBreakComment: 10\nPenaltyBreakFirstLessLess: 0\nPenaltyBreakString: 10\nPenaltyExcessCharacter: 100\nPenaltyReturnTypeOnItsOwnLine: 60\n\nPointerAlignment: Right\nReflowComments: false\nSortIncludes: false\nSortUsingDeclarations: false\nSpaceAfterCStyleCast: false\nSpaceAfterTemplateKeyword: true\nSpaceBeforeAssignmentOperators: true\nSpaceBeforeCtorInitializerColon: true\nSpaceBeforeInheritanceColon: true\nSpaceBeforeParens: ControlStatementsExceptForEachMacros\nSpaceBeforeRangeBasedForLoopColon: true\nSpaceInEmptyParentheses: false\nSpacesBeforeTrailingComments: 1\nSpacesInAngles: false\nSpacesInContainerLiterals: false\nSpacesInCStyleCastParentheses: false\nSpacesInParentheses: false\nSpacesInSquareBrackets: false\nStandard: Cpp03\nTabWidth: 8\nUseTab: Always\n...\n"
  },
  {
    "path": "samples/.gitignore",
    "content": "*/loader\n*/event-trigger\n*/src/linux\n*/src/stub.rs\n*/target\n*/.gdbinit\n*/.gdb_history\n*/syscall_tp\n"
  },
  {
    "path": "samples/atomic/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/atomic/Cargo.toml",
    "content": "[package]\nname = \"atomic\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/atomic/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/atomic/event-trigger.c",
    "content": "#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\nint main(int argc, char *argv[])\n{\n\tint nr_rounds, arg, fd;\n\n\tif (argc != 3)\n\t\tasm volatile(\"ud2\");\n\n\tnr_rounds = atoi(argv[1]);\n\targ = atoi(argv[2]);\n\tfd = open(\"/proc/kprobe_target\", O_RDONLY);\n\tif (fd < 0) {\n\t\tperror(\"open\");\n\t\treturn 1;\n\t}\n\n\tfor (int i = 0; i < nr_rounds; i++)\n\t\tioctl(fd, 1313, arg);\n\n\tclose(fd);\n}\n"
  },
  {
    "path": "samples/atomic/loader.c",
    "content": "#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\n#include <linux/perf_event.h>\n#include <linux/unistd.h>\n\n#include <librex.h>\n#include <bpf/libbpf.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/atomic\"\n\nint main(void)\n{\n\tstruct bpf_object *obj;\n\tstruct bpf_program *prog;\n\tstruct bpf_link *link = NULL;\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\tprog = bpf_object__find_program_by_name(obj, \"rex_prog1\");\n\tif (!prog) {\n\t\tfprintf(stderr, \"Program not found\\n\");\n\t\treturn 1;\n\t}\n\n\tlink = bpf_program__attach(prog);\n\tif (libbpf_get_error(link)) {\n\t\tfprintf(stderr, \"ERROR: bpf_program__attach failed\\n\");\n\t\tlink = NULL;\n\t\treturn 1;\n\t}\n\n\tbpf_link__pin(link, \"/sys/fs/bpf/link\");\n\tbpf_link__destroy(link);\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/atomic/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nsample_clippy = custom_target(\n  'atomic-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsample_build = custom_target(\n  'atomic-build',\n  output: ['atomic'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nexecutable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\nexecutable(\n  'event-trigger',\n  'event-trigger.c',\n  build_by_default: true,\n  dependencies: [kernel_dep],\n  pie: true\n)\n"
  },
  {
    "path": "samples/atomic/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/atomic/src/main.rs",
    "content": "#![no_std]\n#![no_main]\nextern crate rex;\n\nuse core::sync::atomic::{AtomicU64, Ordering};\n\nuse rex::kprobe::*;\nuse rex::pt_regs::PtRegs;\nuse rex::{Result, rex_kprobe, rex_printk};\n\nstatic ATOM: AtomicU64 = AtomicU64::new(42);\n\n#[rex_kprobe(function = \"kprobe_target_func\")]\nfn rex_prog1(obj: &kprobe, _ctx: &mut PtRegs) -> Result {\n    let random = obj.bpf_get_prandom_u32() as u64;\n    ATOM.store(random, Ordering::Relaxed);\n\n    let start = obj.bpf_ktime_get_ns();\n    let val = ATOM.load(Ordering::Relaxed);\n    let end = obj.bpf_ktime_get_ns();\n\n    rex_printk!(\"Time elapsed: {} {}\", end - start, val)?;\n\n    Ok(0)\n}\n"
  },
  {
    "path": "samples/bmc/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/bmc/Cargo.toml",
    "content": "[package]\nname = \"bmc\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n\n"
  },
  {
    "path": "samples/bmc/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/bmc/entry.c",
    "content": "#include <bpf/bpf.h>\n#include <bpf/libbpf.h>\n#include <linux/bpf.h>\n#include <linux/if_link.h>\n#include <linux/limits.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/resource.h>\n#include <time.h>\n#include <unistd.h>\n#include <assert.h>\n\n#include <librex.h>\n\n#define BPF_SYSFS_ROOT \"/sys/fs/bpf\"\n\n#define STATS_PATH \"/tmp/rust_bmc_stats.txt\"\n#define STATS_INTERVAL_PATH \"/tmp/bmc_stats_interval.txt\"\n\n#define EXE \"./target/x86_64-unknown-none/release/bmc\"\n\nstatic int nr_cpus = 0;\n\nstruct bpf_progs_desc {\n\tchar name[256];\n\tenum bpf_prog_type type;\n\tunsigned char pin;\n\tint map_prog_idx;\n\tstruct bpf_program *prog;\n};\n\nstruct bmc_stats {\n\tunsigned int get_recv_count; // Number of GET command received\n\tunsigned int set_recv_count; // Number of SET command received\n\tunsigned int get_resp_count; // Number of GET command reply analyzed\n\tunsigned int\n\t\thit_misprediction; // Number of keys that were expected to hit but did not (either because of a hash colision or a race with an invalidation/update)\n\tunsigned int hit_count; // Number of HIT in kernel cache\n\tunsigned int miss_count; // Number of MISS in kernel cache\n\tunsigned int update_count; // Number of kernel cache updates\n\tunsigned int\n\t\tinvalidation_count; // Number of kernel cache entry invalidated\n\tunsigned int debug_count;\n};\n\nstatic int libbpf_print_fn(enum libbpf_print_level level, const char *format,\n\t\t\t   va_list args)\n{\n\tif (level == LIBBPF_DEBUG || level == LIBBPF_INFO) {\n\t\treturn vfprintf(stderr, format, args);\n\t}\n\treturn 0;\n}\n\nint write_stats_to_file(char *filename, int map_fd)\n{\n\tstruct bmc_stats stats[nr_cpus];\n\tstruct bmc_stats aggregate_stats;\n\t__u32 key = 0;\n\tFILE *fp;\n\n\tmemset(&aggregate_stats, 0, sizeof(struct bmc_stats));\n\n\tassert(bpf_map_lookup_elem(map_fd, &key, stats) == 0);\n\tfor (int i = 0; i < nr_cpus; i++) {\n\t\taggregate_stats.get_recv_count += stats[i].get_recv_count;\n\t\taggregate_stats.set_recv_count += stats[i].set_recv_count;\n\t\taggregate_stats.get_resp_count += stats[i].get_resp_count;\n\t\taggregate_stats.hit_misprediction += stats[i].hit_misprediction;\n\t\taggregate_stats.hit_count += stats[i].hit_count;\n\t\taggregate_stats.miss_count += stats[i].miss_count;\n\t\taggregate_stats.update_count += stats[i].update_count;\n\t\taggregate_stats.invalidation_count +=\n\t\t\tstats[i].invalidation_count;\n\t\taggregate_stats.debug_count += stats[i].debug_count;\n\t}\n\n\tfp = fopen(STATS_PATH, \"w+\");\n\tif (fp == NULL) {\n\t\tfprintf(stderr, \"Error: failed to write stats to file '%s'\\n\",\n\t\t\tfilename);\n\t\treturn -1;\n\t}\n\n\tfprintf(fp, \"STAT get_recv_count %u\\n\", aggregate_stats.get_recv_count);\n\tfprintf(fp, \"STAT set_recv_count %u\\n\", aggregate_stats.set_recv_count);\n\tfprintf(fp, \"STAT get_resp_count %u\\n\", aggregate_stats.get_resp_count);\n\tfprintf(fp, \"STAT hit_misprediction %u\\n\",\n\t\taggregate_stats.hit_misprediction);\n\tfprintf(fp, \"STAT hit_count %u\\n\", aggregate_stats.hit_count);\n\tfprintf(fp, \"STAT miss_count %u\\n\", aggregate_stats.miss_count);\n\tfprintf(fp, \"STAT update_count %u\\n\", aggregate_stats.update_count);\n\tfprintf(fp, \"STAT invalidation_count %u\\n\",\n\t\taggregate_stats.invalidation_count);\n\tfprintf(fp, \"STAT debug_count %u\\n\", aggregate_stats.debug_count);\n\tfclose(fp);\n\treturn 0;\n}\n\nint main(int argc, char *argv[])\n{\n\tstruct rlimit r = { RLIM_INFINITY, RLIM_INFINITY };\n\tint xdp_main_prog_fd;\n\tstruct bpf_program *rx_prog, *tx_prog;\n\tstruct bpf_object *obj;\n\tchar filename[PATH_MAX];\n\tint err;\n\t__u32 xdp_flags = 0;\n\tint *interfaces_idx;\n\tint ret = 0;\n\n\tint interface_count = 0;\n\tint sig, quit = 0;\n\n\tlibbpf_set_print(libbpf_print_fn);\n\n\tinterface_count = argc - optind;\n\tif (interface_count <= 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Missing at least one required interface index\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tinterfaces_idx = calloc(sizeof(int), interface_count);\n\tif (interfaces_idx == NULL) {\n\t\tfprintf(stderr, \"Error: failed to allocate memory\\n\");\n\t\treturn 1;\n\t}\n\n\tfor (int i = 0; i < interface_count && optind < argc; optind++, i++) {\n\t\tinterfaces_idx[i] = atoi(argv[optind]);\n\t}\n\tnr_cpus = libbpf_num_possible_cpus();\n\n\tsigset_t signal_mask;\n\tsigemptyset(&signal_mask);\n\tsigaddset(&signal_mask, SIGINT);\n\tsigaddset(&signal_mask, SIGTERM);\n\tsigaddset(&signal_mask, SIGUSR1);\n\n\tif (setrlimit(RLIMIT_MEMLOCK, &r)) {\n\t\tperror(\"setrlimit failed\");\n\t\treturn 1;\n\t}\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\trx_prog = bpf_object__find_program_by_name(obj, \"xdp_rx_filter\");\n\tif (!rx_prog) {\n\t\tfprintf(stderr, \"start not found\\n\");\n\t\treturn 1;\n\t}\n\n\txdp_main_prog_fd = bpf_program__fd(rx_prog);\n\tif (xdp_main_prog_fd < 0) {\n\t\tfprintf(stderr, \"Error: bpf_program__fd failed\\n\");\n\t\treturn 1;\n\t}\n\n\txdp_flags |= XDP_FLAGS_DRV_MODE;\n\t/* xdp_flags |= XDP_FLAGS_SKB_MODE; */\n\tfor (int i = 0; i < interface_count; i++) {\n\t\tif (bpf_xdp_attach(interfaces_idx[i], xdp_main_prog_fd,\n\t\t\t\t   xdp_flags, NULL) < 0) {\n\t\t\tfprintf(stderr,\n\t\t\t\t\"Error: bpf_set_link_xdp_fd failed for interface %d\\n\",\n\t\t\t\tinterfaces_idx[i]);\n\t\t\treturn 1;\n\t\t} else {\n\t\t\tprintf(\"Main BPF program attached to XDP on interface %d\\n\",\n\t\t\t       interfaces_idx[i]);\n\t\t}\n\t}\n\n\tchar prog_name[256] = \"xdp_tx_filter\";\n\ttx_prog = bpf_object__find_program_by_name(obj, prog_name);\n\tif (!tx_prog) {\n\t\tfprintf(stderr, \"tx_prog not found\\n\");\n\t\texit(1);\n\t}\n\tprintf(\"tx_prog: %s\\n\", bpf_program__name(tx_prog));\n\n\tint len = snprintf(filename, PATH_MAX, \"%s/%s\", BPF_SYSFS_ROOT,\n\t\t\t   prog_name);\n\tif (len < 0) {\n\t\tfprintf(stderr, \"Error: Program name '%s' is invalid\\n\",\n\t\t\t\"xdp_tx_filter\");\n\t\treturn -1;\n\t} else if (len >= PATH_MAX) {\n\t\tfprintf(stderr, \"Error: Program name '%s' is too long\\n\",\n\t\t\tprog_name);\n\t\treturn -1;\n\t}\n\n\tret = bpf_program__pin(tx_prog, filename);\n\tif (ret != 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Error: Failed to pin program '%s' to path %s with error code %d\\n\",\n\t\t\tprog_name, filename, ret);\n\t\treturn ret;\n\t}\n\n\terr = sigprocmask(SIG_BLOCK, &signal_mask, NULL);\n\tif (err != 0) {\n\t\tfprintf(stderr, \"Error: Failed to set signal mask\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\twhile (!quit) {\n\t\terr = sigwait(&signal_mask, &sig);\n\t\tif (err != 0) {\n\t\t\tfprintf(stderr, \"Error: Failed to wait for signal\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tswitch (sig) {\n\t\tcase SIGINT:\n\t\tcase SIGTERM:\n\t\tcase SIGUSR1:\n\t\t\tquit = 1;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Unknown signal\\n\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tint map_stats_fd = bpf_object__find_map_fd_by_name(obj, \"map_stats\");\n\tif (map_stats_fd < 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Error: bpf_object__find_map_fd_by_name failed\\n\");\n\t\treturn 1;\n\t}\n\n\tprintf(\"Writing stats to file\\n\");\n\twrite_stats_to_file(STATS_PATH, map_stats_fd);\n\n\tfor (int i = 0; i < interface_count; i++) {\n\t\tbpf_xdp_attach(interfaces_idx[i], -1, xdp_flags, NULL);\n\t}\n\treturn ret;\n}\n"
  },
  {
    "path": "samples/bmc/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nsample_clippy = custom_target(\n  'bmc-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsample_build = custom_target(\n  'bmc-build',\n  output: ['bmc'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nexecutable(\n  'entry',\n  'entry.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n"
  },
  {
    "path": "samples/bmc/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/bmc/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n#![allow(non_camel_case_types)]\n\nuse core::mem::{size_of, swap};\n\nuse rex::map::*;\nuse rex::sched_cls::*;\nuse rex::spinlock::*;\nuse rex::utils::*;\nuse rex::xdp::*;\nuse rex::{rex_map, rex_printk, rex_tc, rex_xdp};\n\nconst BMC_MAX_PACKET_LENGTH: usize = 1500;\nconst BMC_CACHE_ENTRY_COUNT: u32 = 3250000;\nconst BMC_MAX_KEY_LENGTH: usize = 230;\nconst BMC_MAX_VAL_LENGTH: usize = 1000;\nconst BMC_MAX_ADDITIONAL_PAYLOAD_BYTES: usize = 53;\nconst BMC_MAX_CACHE_DATA_SIZE: usize =\n    BMC_MAX_KEY_LENGTH + BMC_MAX_VAL_LENGTH + BMC_MAX_ADDITIONAL_PAYLOAD_BYTES;\nconst BMC_MAX_KEY_IN_PACKET: u32 = 30;\n\nconst FNV_OFFSET_BASIS_32: u32 = 2166136261;\nconst FNV_PRIME_32: u32 = 16777619;\nconst ETH_ALEN: usize = 6;\nconst MEMCACHED_PORT: u16 = 11211;\n\n#[repr(C)]\npub struct memcached_udp_header {\n    request_id: u16,\n    seq_num: u16,\n    num_dgram: u16,\n    unused: u16,\n}\n\n#[repr(C)]\n#[derive(Clone, Copy)]\npub struct bmc_cache_entry {\n    lock: bpf_spin_lock,\n    pub len: u32,\n    pub valid: u8,\n    pub hash: u32,\n    pub data: [u8; BMC_MAX_PACKET_LENGTH],\n}\n\n#[repr(C)]\n#[derive(Clone, Copy)]\nstruct memcached_key {\n    hash: u32,\n    data: [u8; BMC_MAX_KEY_LENGTH],\n    len: usize,\n}\n\n#[repr(C)]\n#[derive(Clone, Copy)]\npub struct bmc_stats {\n    get_recv_count: u32,\n    set_recv_count: u32,\n    get_resp_count: u32,\n    hit_misprediction: u32,\n    hit_count: u32,\n    miss_count: u32,\n    update_count: u32,\n    invalidation_count: u32,\n    debug_count: u32,\n}\n\nstruct parsing_context {\n    key_count: u32,\n    current_key: u32,\n    read_pkt_offset: u8,\n}\n\n#[rex_map]\nstatic map_kcache: RexArrayMap<bmc_cache_entry> =\n    RexArrayMap::new(BMC_CACHE_ENTRY_COUNT, 0);\n\n#[rex_map]\nstatic map_keys: RexPerCPUArrayMap<memcached_key> =\n    RexPerCPUArrayMap::new(BMC_MAX_KEY_IN_PACKET, 0);\n\n#[rex_map]\nstatic map_stats: RexPerCPUArrayMap<bmc_stats> = RexPerCPUArrayMap::new(1, 0);\n\n// TODO: use simple hash function, may need update in the future\nmacro_rules! hash_func {\n    ($hash:expr, $value:expr) => {\n        $hash = ($hash ^ $value as u32).wrapping_mul(FNV_PRIME_32);\n    };\n}\n\nmacro_rules! swap_field {\n    ($field1:expr, $field2:expr, $size:ident) => {\n        for i in 0..$size {\n            swap(&mut $field1[i], &mut $field2[i])\n        }\n    };\n}\n\n// payload after header and 'get '\n#[inline(always)]\nfn hash_key(\n    obj: &xdp,\n    ctx: &mut xdp_md,\n    pctx: &mut parsing_context,\n    payload_index: usize,\n    stats: &mut bmc_stats,\n) -> Result {\n    let payload = &ctx.data_slice[payload_index..];\n    let mut done_parsing = false;\n\n    while !done_parsing {\n        let key = obj\n            .bpf_map_lookup_elem(&map_keys, &pctx.key_count)\n            .ok_or(0i32)?;\n\n        key.hash = FNV_OFFSET_BASIS_32;\n\n        let payload = &payload[..(BMC_MAX_KEY_LENGTH + 1)\n            .min(ctx.data_length() - pctx.read_pkt_offset as usize)];\n\n        let key_len = payload\n            .iter()\n            .take_while(|&&byte| byte != b'\\r' && byte != b' ')\n            .inspect(|&&byte| {\n                hash_func!(key.hash, byte);\n            })\n            .count(); // Returns the number of elements processed, effectively the key length\n\n        done_parsing = payload[key_len] == b'\\r';\n\n        // no key found\n        if key_len == 0 || key_len > BMC_MAX_KEY_LENGTH {\n            return Ok(XDP_PASS as i32);\n        }\n\n        // get the cache entry\n        let cache_idx: u32 = key.hash % BMC_CACHE_ENTRY_COUNT;\n        let entry = obj\n            .bpf_map_lookup_elem(&map_kcache, &cache_idx)\n            .ok_or(0i32)?;\n\n        let entry_valid;\n        {\n            let _guard = rex_spinlock_guard::new(&mut entry.lock);\n            entry_valid = entry.valid == 1 && entry.hash == key.hash\n        }\n\n        // potential cache hit\n        if entry_valid {\n            key.data[0..key_len].clone_from_slice(&payload[0..key_len]);\n            key.len = key_len;\n            pctx.key_count += 1;\n        } else {\n            // cache miss\n            stats.miss_count += 1;\n        }\n\n        if done_parsing && pctx.key_count > 0 {\n            {\n                let eth_header: &mut ethhdr = &mut obj.eth_header(ctx);\n                // exchange src and dst ip and mac\n                swap_field!(eth_header.h_dest, eth_header.h_source, ETH_ALEN);\n            }\n\n            {\n                let mut ip_header_mut = obj.ip_header(ctx);\n                let temp: u32 = *ip_header_mut.saddr();\n                *ip_header_mut.saddr() = *ip_header_mut.daddr();\n                *ip_header_mut.daddr() = temp;\n            }\n\n            {\n                let udp_header: &mut udphdr = &mut obj.udp_header(ctx);\n                swap(&mut udp_header.source, &mut udp_header.dest);\n            }\n\n            return write_pkt_reply(obj, ctx, payload_index, pctx, stats);\n        }\n        // process more keys\n        pctx.read_pkt_offset += key_len as u8 + 1;\n    }\n\n    Ok(XDP_PASS as i32)\n}\n\n// payload after headers and 'get '\n#[inline(always)]\nfn write_pkt_reply(\n    obj: &xdp,\n    ctx: &mut xdp_md,\n    payload_index: usize,\n    pctx: &mut parsing_context,\n    stats: &mut bmc_stats,\n) -> Result {\n    let key = obj\n        .bpf_map_lookup_elem(&map_keys, &pctx.current_key)\n        .ok_or(XDP_PASS as i32)?;\n\n    let (mut cache_hit, _written) = (false, 0u32);\n\n    let cache_idx = key.hash % BMC_CACHE_ENTRY_COUNT;\n    let entry = obj\n        .bpf_map_lookup_elem(&map_kcache, &cache_idx)\n        .ok_or(XDP_DROP as i32)?;\n\n    let _guard = rex_spinlock_guard::new(&mut entry.lock);\n\n    if entry.valid == 1 && entry.hash == key.hash {\n        if key.len >= BMC_MAX_KEY_LENGTH {\n            cache_hit = false;\n        } else {\n            let entry_data_key = &entry.data[6..6 + key.len];\n            cache_hit = key\n                .data\n                .iter()\n                .zip(entry_data_key.iter())\n                .all(|(a, b)| a == b);\n            if !cache_hit {\n                stats.hit_misprediction += 1;\n            }\n        }\n    }\n\n    // copy cache data\n    if cache_hit {\n        let _off = 0usize;\n        let stats = obj.bpf_map_lookup_elem(&map_stats, &0).ok_or(0i32)?;\n        stats.hit_count += 1;\n\n        // NOTE: data end is determined by slice length limit, may changed in\n        // future while off + U64_SIZE < BMC_MAX_CACHE_DATA_SIZE && off\n        // + U64_SIZE <= entry.len as usize {}\n        let padding =\n            (entry.len as i32 - (ctx.data_length() - payload_index) as i32) + 1;\n\n        match obj.bpf_xdp_adjust_tail(ctx, padding) {\n            Ok(_) => {}\n            Err(_) => {\n                rex_printk!(\"adjust tail failed\\n\")?;\n                return Ok(XDP_DROP as i32);\n            }\n        }\n\n        // INFO: currently only support single key\n\n        {\n            // udp check not required\n            let mut ip_header_mut = obj.ip_header(ctx);\n            ip_header_mut.tot_len =\n                (u16::from_be(ip_header_mut.tot_len) + padding as u16).to_be();\n            ip_header_mut.check = compute_ip_checksum(&mut ip_header_mut);\n        }\n\n        {\n            let mut udp_header = obj.udp_header(ctx);\n            udp_header.len =\n                (u16::from_be(udp_header.len) + padding as u16).to_be();\n            udp_header.check = 0;\n        }\n\n        let payload = &mut ctx.data_slice[payload_index - 4..];\n        payload[0..entry.len as usize]\n            .clone_from_slice(&entry.data[0..entry.len as usize]);\n\n        let end = b\"END\\r\\n\";\n        for i in entry.len as usize..(entry.len + 5) as usize {\n            payload[i] = end[i - entry.len as usize];\n        }\n    } else {\n        stats.miss_count += 1;\n    }\n\n    Ok(XDP_TX as i32)\n}\n\n#[inline(always)]\nfn bmc_invalidate_cache(obj: &xdp, ctx: &mut xdp_md) -> Result {\n    let header_len =\n        size_of::<ethhdr>() + size_of::<iphdr>() + size_of::<tcphdr>();\n\n    let tcp_header = obj.tcp_header(ctx);\n    let port = u16::from_be(tcp_header.dest);\n    drop(tcp_header);\n\n    // start after the tcp header\n    let payload = &ctx.data_slice[header_len..];\n\n    // check if using the memcached port\n    // check if the payload has enough space for a memcached request\n    if port != MEMCACHED_PORT || payload.len() < 4 {\n        return Ok(XDP_PASS as i32);\n    }\n\n    // get the index for the set command in the payload\n    let set_iter = payload\n        .windows(4)\n        .enumerate()\n        .filter_map(|(i, v)| if v == b\"set \" { Some(i) } else { None });\n\n    // iterate through the possible set commands\n    for index in set_iter {\n        let stats = obj.bpf_map_lookup_elem(&map_stats, &0).ok_or(0i32)?;\n        stats.set_recv_count += 1;\n\n        let mut hash = FNV_OFFSET_BASIS_32;\n        let payload = &payload[index + 4..];\n\n        // limit the size of key\n        // hash the key until the first space\n        payload.iter().take_while(|&&c| c != b' ').for_each(|&c| {\n            hash_func!(hash, c);\n        });\n\n        // get the cache entry\n        let cache_idx: u32 = hash % BMC_CACHE_ENTRY_COUNT;\n\n        let entry = obj\n            .bpf_map_lookup_elem(&map_kcache, &cache_idx)\n            .ok_or(0i32)?;\n        if entry.valid == 1 {\n            stats.invalidation_count += 1;\n            let _guard = rex_spinlock_guard::new(&mut entry.lock);\n            entry.valid = 0;\n        }\n    }\n\n    Ok(XDP_PASS as i32)\n}\n\n#[rex_xdp]\nfn xdp_rx_filter(obj: &xdp, ctx: &mut xdp_md) -> Result {\n    let iphdr = obj.ip_header(ctx);\n    let protocol = iphdr.protocol;\n    drop(iphdr);\n\n    match u8::from_be(protocol) as u32 {\n        IPPROTO_TCP => {\n            return bmc_invalidate_cache(obj, ctx);\n        }\n        IPPROTO_UDP => {\n            let header_len = size_of::<ethhdr>() +\n                size_of::<iphdr>() +\n                size_of::<udphdr>() +\n                size_of::<memcached_udp_header>();\n            let udp_header = obj.udp_header(ctx);\n            let port = u16::from_be(udp_header.dest);\n            drop(udp_header);\n\n            let payload = &ctx.data_slice[header_len..];\n\n            // check if using the memcached port\n            // check if the payload has enough space for a memcached request\n            if port != MEMCACHED_PORT || payload.len() < 4 {\n                return Ok(XDP_PASS as i32);\n            }\n\n            // check if a get command\n            if !payload.starts_with(b\"get \") {\n                return Ok(XDP_PASS as i32);\n            }\n\n            let stats = obj\n                .bpf_map_lookup_elem(&map_stats, &0)\n                .ok_or(XDP_PASS as i32)?;\n            stats.get_recv_count += 1;\n\n            let mut off = 4;\n            // move offset to the start of the first key\n            while off < BMC_MAX_PACKET_LENGTH &&\n                off + 1 < payload.len() &&\n                payload[off] == b' '\n            {\n                off += 1;\n            }\n            off += header_len;\n\n            let mut pctx = parsing_context {\n                key_count: 0,\n                current_key: 0,\n                read_pkt_offset: off as u8,\n            };\n\n            // TODO: not sure if there is a better way\n            return hash_key(obj, ctx, &mut pctx, off, stats);\n        }\n        _ => {}\n    };\n\n    Ok(XDP_PASS as i32)\n}\n\n// payload after all headers\n#[inline(always)]\nfn bmc_update_cache(\n    obj: &sched_cls,\n    skb: &__sk_buff,\n    payload: &[u8],\n    header_len: usize,\n    stats: &mut bmc_stats,\n) -> Result {\n    let mut hash = FNV_OFFSET_BASIS_32;\n\n    let mut off = 6usize;\n    while off < BMC_MAX_KEY_LENGTH &&\n        header_len + off < skb.len() as usize &&\n        payload[off] != b' '\n    {\n        hash_func!(hash, payload[off]);\n        off += 1;\n    }\n    let cache_idx: u32 = hash % BMC_CACHE_ENTRY_COUNT;\n\n    let entry = obj\n        // return TC_ACT_OK if the cache is not found or map error\n        .bpf_map_lookup_elem(&map_kcache, &cache_idx)\n        .ok_or(TC_ACT_OK as i32)?;\n\n    let _guard = rex_spinlock_guard::new(&mut entry.lock);\n\n    // check if the cache is up-to-date\n    if entry.valid == 1 && entry.hash == hash {\n        let mut diff = 0;\n        off = 6;\n        while off < BMC_MAX_KEY_LENGTH &&\n            header_len + off < payload.len() &&\n            (payload[off] != b' ' || entry.data[off] != b' ')\n        {\n            if entry.data[off] != payload[off] {\n                diff = 1;\n                break;\n            }\n            off += 1;\n        }\n\n        // cache is up-to-date, no need to update\n        if diff == 0 {\n            return Ok(TC_ACT_OK as i32);\n        }\n    }\n\n    // cache is not up-to-date, update it\n    entry.len = 0;\n    let mut count = 0;\n    for (i, &payload_data) in\n        payload.iter().enumerate().take(BMC_MAX_CACHE_DATA_SIZE)\n    {\n        if header_len + i >= skb.len() as usize || count >= 2 {\n            break;\n        }\n        entry.data[i] = payload_data;\n        entry.len += 1;\n        if payload_data == b'\\n' {\n            count += 1;\n        }\n    }\n\n    // finished copying\n    if count == 2 {\n        entry.valid = 1;\n        entry.hash = hash;\n        stats.update_count += 1;\n    }\n\n    Ok(TC_ACT_OK as i32)\n}\n\n#[rex_tc]\nfn xdp_tx_filter(obj: &sched_cls, skb: &mut __sk_buff) -> Result {\n    let header_len = size_of::<iphdr>() +\n        size_of::<ethhdr>() +\n        size_of::<udphdr>() +\n        size_of::<memcached_udp_header>();\n\n    if skb.len() as usize <= header_len ||\n        u8::from_be(obj.ip_header(skb).protocol) as u32 != IPPROTO_UDP ||\n        u16::from_be(obj.udp_header(skb).source) != MEMCACHED_PORT ||\n        skb.data_slice.len() < header_len + 6 ||\n        !skb.data_slice[header_len..].starts_with(b\"VALUE \")\n    {\n        return Ok(TC_ACT_OK as i32);\n    }\n    let stats = obj.bpf_map_lookup_elem(&map_stats, &0).ok_or(0i32)?;\n    stats.get_resp_count += 1;\n\n    // update cache map based on the packet\n    let payload = &skb.data_slice[header_len..];\n    bmc_update_cache(obj, skb, payload, header_len, stats)?;\n\n    Ok(TC_ACT_OK as i32)\n}\n"
  },
  {
    "path": "samples/electrode/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/electrode/Cargo.toml",
    "content": "[package]\nname = \"electrode\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n[features]\nfast_reply = []\nfast_quorum_prune = []\ndefault = []\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/electrode/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/electrode/config.txt",
    "content": "f 1\nreplica 10.10.1.1:12345\nreplica 10.10.1.2:12345\nreplica 10.10.1.3:12345\n"
  },
  {
    "path": "samples/electrode/entry.c",
    "content": "#include <arpa/inet.h>\n#include <asm-generic/posix_types.h>\n#include <assert.h>\n#include <bpf/bpf.h>\n#include <bpf/libbpf.h>\n#include <linux/bpf.h>\n#include <linux/if_link.h>\n#include <linux/limits.h>\n#include <netinet/in.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/resource.h>\n#include <sys/socket.h>\n#include <unistd.h>\n\n#include \"fast_common.h\"\n#include <librex.h>\n\n#define BPF_SYSFS_ROOT \"/sys/fs/bpf\"\n\n#define EXE \"./target/x86_64-unknown-none/release/electrode\"\n\nstruct bpf_progs_desc {\n\tchar name[256];\n\tenum bpf_prog_type type;\n\tunsigned char pin;\n\tint map_prog_idx;\n\tstruct bpf_program *prog;\n};\n\nstruct bpf_object *obj;\nstruct bpf_object_load_attr *load_attr;\nstruct bpf_program *rx_prog, *tx_prog;\nstatic int err;\nstatic int xdp_main_prog_fd;\nstatic char filename[PATH_MAX];\nstatic char prog_name[PATH_MAX];\nstatic char commandname[PATH_MAX];\nstatic __u32 xdp_flags = 0;\nstatic int *interfaces_idx;\n\nstruct rlimit r = { RLIM_INFINITY, RLIM_INFINITY };\n\nstatic int map_paxos_ctr_state_fd;\nstatic int map_prepare_buffer_fd, map_configure_fd, map_request_buffer_fd;\nstatic int interface_count = 0;\nstatic int nr_cpus = 0;\n\n// define our eBPF program.\nstatic struct bpf_progs_desc progs[] = {\n\t{ \"fast_paxos_main\", BPF_PROG_TYPE_XDP, 0, -1, NULL },\n\t{ \"fast_broad_cast_main\", BPF_PROG_TYPE_SCHED_CLS, 1, -1, NULL },\n};\n\nstatic int libbpf_print_fn(enum libbpf_print_level level, const char *format,\n\t\t\t   va_list args)\n{\n\tif (level == LIBBPF_DEBUG || level == LIBBPF_INFO)\n\t\treturn vfprintf(stderr, format, args);\n\n\treturn 0;\n}\n\nstatic void read_config(void)\n{\n\tmap_configure_fd =\n\t\tbpf_object__find_map_fd_by_name(obj, \"map_configure\");\n\tif (map_configure_fd < 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Error: bpf_object__find_map_fd_by_name map_configure failed\\n\");\n\t\texit(1); // return 1;\n\t}\n\n\tFILE *fp;\n\tchar buff[255];\n\tint f = 0;\n\n\tstruct sockaddr_in sa;\n\tchar str[INET_ADDRSTRLEN];\n\tstruct paxos_configure conf;\n\n\tconst char *eths[FAST_REPLICA_MAX] = { \"9c:dc:71:56:8f:45\",\n\t\t\t\t\t       \"9c:dc:71:56:bf:45\",\n\t\t\t\t\t       \"9c:dc:71:5e:2f:51\", \"\", \"\" };\n\n\tfp = fopen(\"./config.txt\", \"r\");\n\tif (fp == NULL) {\n\t\tfprintf(stderr, \"Error: failed to open config.txt\\n\");\n\t\texit(1);\n\t}\n\n\t(void)fscanf(fp, \"%s\", buff); // must be 'f'\n\t(void)fscanf(fp, \"%d\", &f);\n\tfor (int i = 0; i < 2 * f + 1; ++i) {\n\t\t(void)fscanf(fp, \"%s\", buff); // must be 'replica'\n\t\t(void)fscanf(fp, \"%s\", buff);\n\n\t\tchar *ipv4 = strtok(buff, \":\");\n\t\tassert(ipv4 != NULL);\n\t\tchar *port = strtok(NULL, \":\");\n\n\t\t// store this IP address in sa:\n\t\tinet_pton(AF_INET, ipv4, &(sa.sin_addr));\n\t\t// now get it back and print it\n\t\tinet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);\n\t\tconf.port = htons(atoi(port));\n\t\tconf.addr = sa.sin_addr.s_addr;\n\t\tsscanf(eths[i], \"%hhx:%hhx:%hhx:%hhx:%hhx:%hhx\", &conf.eth[0],\n\t\t       &conf.eth[1], &conf.eth[2], &conf.eth[3], &conf.eth[4],\n\t\t       &conf.eth[5]);\n\n\t\terr = bpf_map_update_elem(map_configure_fd, &i, &conf, 0);\n\t}\n\n\tfclose(fp);\n\treturn;\n}\n\nstatic void create_object(void)\n{\n\tmap_prepare_buffer_fd =\n\t\tbpf_object__find_map_fd_by_name(obj, \"map_prepare_buffer\");\n\tif (map_prepare_buffer_fd < 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Error: bpf_object__find_map_fd_by_name map_prepare_buffer failed\\n\");\n\t\texit(1); // return 1;\n\t}\n\tmap_request_buffer_fd =\n\t\tbpf_object__find_map_fd_by_name(obj, \"map_request_buffer\");\n\tif (map_request_buffer_fd < 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Error: bpf_object__find_map_fd_by_name map_request_buffer failed\\n\");\n\t\texit(1); // return 1;\n\t}\n\tmap_paxos_ctr_state_fd =\n\t\tbpf_object__find_map_fd_by_name(obj, \"map_ctr_state\");\n\tif (map_paxos_ctr_state_fd < 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Error: bpf_object__find_map_fd_by_name map_ctr_state failed\\n\");\n\t\texit(1); // return 1;\n\t}\n}\n\nstatic void add_interrupt(void)\n{\n\t/* asd123www:\n          !!!!!! the user-space program shouldn't quit here.\n                          Otherwise the program will be lost, due to fd lost???\n\t*/\n\tsigset_t signal_mask;\n\tsigemptyset(&signal_mask);\n\tsigaddset(&signal_mask, SIGINT);\n\tsigaddset(&signal_mask, SIGTERM);\n\tsigaddset(&signal_mask, SIGUSR1);\n\n\tint sig, quit = 0;\n\t// FILE *fp = NULL;\n\n\terr = sigprocmask(SIG_BLOCK, &signal_mask, NULL);\n\tif (err != 0) {\n\t\tfprintf(stderr, \"Error: Failed to set signal mask\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\twhile (!quit) {\n\t\terr = sigwait(&signal_mask, &sig);\n\t\tif (err != 0) {\n\t\t\tfprintf(stderr, \"Error: Failed to wait for signal\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tswitch (sig) {\n\t\tcase SIGINT:\n\t\tcase SIGTERM:\n\t\t\tquit = 1;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Unknown signal\\n\");\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn;\n}\n\nint main(int argc, char *argv[])\n{\n\tint ret = 0;\n\tlibbpf_set_print(libbpf_print_fn);\n\trex_set_debug(1); // enable debug info\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\tinterface_count = argc - optind;\n\tif (interface_count <= 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Missing at least one required interface index\\n\");\n\t\treturn 1;\n\t}\n\n\tinterfaces_idx = calloc(sizeof(int), interface_count);\n\tif (interfaces_idx == NULL) {\n\t\tfprintf(stderr, \"Error: failed to allocate memory\\n\");\n\t\treturn 1;\n\t}\n\n\tfor (int i = 0; i < interface_count && optind < argc; optind++, i++)\n\t\tinterfaces_idx[i] = atoi(argv[optind]);\n\n\tnr_cpus = libbpf_num_possible_cpus();\n\n\tif (setrlimit(RLIMIT_MEMLOCK, &r)) {\n\t\tperror(\"setrlimit failed\");\n\t\treturn 1;\n\t}\n\n\tcreate_object();\n\tread_config();\n\tassert(bpf_obj_pin(map_prepare_buffer_fd,\n\t\t\t   \"/sys/fs/bpf/paxos_prepare_buffer\") == 0);\n\tassert(bpf_obj_pin(map_request_buffer_fd,\n\t\t\t   \"/sys/fs/bpf/paxos_request_buffer\") == 0);\n\tassert(bpf_obj_pin(map_paxos_ctr_state_fd,\n\t\t\t   \"/sys/fs/bpf/paxos_ctr_state\") == 0);\n\n\trx_prog = bpf_object__find_program_by_name(obj, progs[0].name);\n\tif (!rx_prog) {\n\t\tfprintf(stderr, \"start not found\\n\");\n\t\texit(1);\n\t}\n\n\txdp_main_prog_fd = bpf_program__fd(rx_prog);\n\tif (xdp_main_prog_fd < 0) {\n\t\tfprintf(stderr, \"Error: bpf_program__fd failed\\n\");\n\t\treturn 1;\n\t}\n\n\txdp_flags |= XDP_FLAGS_DRV_MODE;\n\t/* xdp_flags |= XDP_FLAGS_SKB_MODE; */\n\tfor (int i = 0; i < interface_count; i++) {\n\t\tif (bpf_xdp_attach(interfaces_idx[i], xdp_main_prog_fd,\n\t\t\t\t   xdp_flags, NULL) < 0) {\n\t\t\tfprintf(stderr,\n\t\t\t\t\"Error: bpf_set_link_xdp_fd failed for interface %d\\n\",\n\t\t\t\tinterfaces_idx[i]);\n\t\t\treturn 1;\n\t\t} else {\n\t\t\tprintf(\"Main BPF program attached to XDP on interface %d\\n\",\n\t\t\t       interfaces_idx[i]);\n\t\t}\n\t}\n\n\ttx_prog = bpf_object__find_program_by_name(obj, progs[1].name);\n\tif (!tx_prog) {\n\t\tfprintf(stderr, \"tx_prog not found\\n\");\n\t\texit(1);\n\t}\n\tprintf(\"tx_prog: %s\\n\", bpf_program__name(tx_prog));\n\n\tint len = snprintf(filename, PATH_MAX, \"%s/%s\", BPF_SYSFS_ROOT,\n\t\t\t   progs[1].name);\n\tif (len < 0) {\n\t\tfprintf(stderr, \"Error: Program name '%s' is invalid\\n\",\n\t\t\t\"xdp_tx_filter\");\n\t\treturn -1;\n\t} else if (len >= PATH_MAX) {\n\t\tfprintf(stderr, \"Error: Program name '%s' is too long\\n\",\n\t\t\tprogs[1].name);\n\t\treturn -1;\n\t}\n\n\t// pin sched_cls\n\tret = bpf_program__pin(tx_prog, filename);\n\tif (ret != 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Error: Failed to pin program '%s' to path %s with error code %d\\n\",\n\t\t\tprog_name, filename, ret);\n\t\treturn ret;\n\t}\n\n\tfor (int i = 0; i < interface_count && optind < argc; i++) {\n\t\tsnprintf(commandname, PATH_MAX, \"tc qdisc add dev %s clsact\",\n\t\t\t argv[optind + i]);\n\t\tassert(system(commandname) == 0);\n\t\tsnprintf(commandname, PATH_MAX,\n\t\t\t \"tc filter add dev %s egress bpf object-pinned \"\n\t\t\t \"/sys/fs/bpf/FastBroadCast\",\n\t\t\t argv[optind + i]);\n\t\tassert(system(commandname) == 0);\n\t\tprintf(\"Main BPF program attached to TC on interface %d\\n\",\n\t\t       interfaces_idx[i]);\n\t}\n\n\tadd_interrupt();\n\n\tassert(remove(\"/sys/fs/bpf/paxos_prepare_buffer\") == 0);\n\tassert(remove(\"/sys/fs/bpf/paxos_request_buffer\") == 0);\n\tassert(remove(\"/sys/fs/bpf/paxos_ctr_state\") == 0);\n\n\tfor (int i = 0; i < interface_count; i++)\n\t\tbpf_xdp_attach(interfaces_idx[i], -1, xdp_flags, NULL);\n\n\tfor (int i = 0; i < interface_count && optind < argc; i++) {\n\t\tsnprintf(commandname, PATH_MAX, \"tc filter del dev %s egress\",\n\t\t\t argv[optind + i]);\n\t\tassert(system(commandname) == 0);\n\t\tsnprintf(commandname, PATH_MAX, \"tc qdisc del dev %s clsact\",\n\t\t\t argv[optind + i]);\n\t\tassert(system(commandname) == 0);\n\t}\n\n\tassert(remove(\"/sys/fs/bpf/fast_broad_cast_main\") == 0);\n\tprintf(\"\\nasd123www: quit safely!\\n\");\n\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/electrode/fast_common.h",
    "content": "/*\n *  Software Name : fast-paxos\n *  SPDX-FileCopyrightText: Copyright (c) 2022 Orange\n *  SPDX-License-Identifier: LGPL-2.1-only\n *\n *  This software is distributed under the\n *  GNU Lesser General Public License v2.1 only.\n *\n *  Author: asd123www <wzz@pku.edu.cn> et al.\n */\n\n#ifndef _FAST_COMMON_H\n#define _FAST_COMMON_H\n\n#define ETH_ALEN 6 /* Octets in one ethernet addr\t */\n\n#define CLUSTER_SIZE 3        // need\n#define FAST_REPLICA_MAX 100  // max # of replicas.\n#define NONFRAG_MAGIC 0x20050318\n#define FRAG_MAGIC 0x20101010\n\n#define MAGIC_LEN 4\n#define REQUEST_TYPE_LEN 33\n#define PREPARE_TYPE_LEN 33\n#define PREPAREOK_TYPE_LEN 35\n#define MYPREPAREOK_TYPE_LEN 24\n\n#define FAST_PAXOS_DATA_LEN 12\n#define BROADCAST_SIGN_BIT (1 << 31)\n#define QUORUM_SIZE ((CLUSTER_SIZE + 1) >> 1)\n#define QUORUM_BITSET_ENTRY 1024  // must be 2^t\n\nenum ReplicaStatus { STATUS_NORMAL, STATUS_VIEW_CHANGE, STATUS_RECOVERING };\n\nenum {\n  FAST_PROG_XDP_HANDLE_PREPARE = 0,\n  FAST_PROG_XDP_HANDLE_REQUEST,\n  FAST_PROG_XDP_HANDLE_PREPAREOK,\n  FAST_PROG_XDP_WRITE_BUFFER,\n  FAST_PROG_XDP_PREPARE_REPLY,\n\n  FAST_PROG_XDP_MAX\n};\n\nenum {\n  FAST_PROG_TC_BROADCAST = 0,\n\n  FAST_PROG_TC_MAX\n};\n\nstruct paxos_configure {\n  __u32 addr;  // ipv4.\n  __u16 port;\n  char eth[ETH_ALEN];\n};\n\n#endif\n"
  },
  {
    "path": "samples/electrode/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nsample_clippy = custom_target(\n  'electrode-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nelectrode_config = custom_target(\n  'config.txt',\n  input: 'config.txt',\n  output: ['config.txt'],\n  command: ['cp', '@INPUT@', '@OUTPUT@'],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsample_build = custom_target(\n  'electrode-build',\n  output: ['electrode'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: [sample_clippy, electrode_config],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nexecutable(\n  'entry',\n  'entry.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n"
  },
  {
    "path": "samples/electrode/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/electrode/src/common.rs",
    "content": "#![allow(unused)]\n//\n// Software Name : fast-paxos\n// SPDX-FileCopyrightText: Copyright (c) 2022 Orange\n// SPDX-License-Identifier: LGPL-2.1-only\n//\n// This software is distributed under the\n// GNU Lesser General Public License v2.1 only.\n//\n// Author: asd123www <wzz@pku.edu.cn> et al.\n// Author: Ruowen Qin <ruowenq2@illinois.edu> et al.\n//\n\npub(crate) const ETH_ALEN: usize = 6; // Octets in one ethernet addr\npub(crate) const MTU: u64 = 1500;\npub(crate) const MAX_DATA_LEN: usize = 64;\n\npub(crate) const CLUSTER_SIZE: u8 = 3;\npub(crate) const FAST_REPLICA_MAX: u32 = 100; // max # of replicas.\npub(crate) const NONFRAG_MAGIC: u32 = 0x20050318;\npub(crate) const FRAG_MAGIC: u32 = 0x20101010;\n\npub(crate) const MAGIC_LEN: usize = 4;\npub(crate) const REQUEST_TYPE_LEN: usize = 33;\npub(crate) const PREPARE_TYPE_LEN: usize = 33;\npub(crate) const PREPAREOK_TYPE_LEN: usize = 35;\npub(crate) const MYPREPAREOK_TYPE_LEN: usize = 24;\n\npub(crate) const FAST_PAXOS_DATA_LEN: usize = 12;\npub(crate) const BROADCAST_SIGN_BIT: u32 = 1 << 31;\npub(crate) const QUORUM_SIZE: u32 = (CLUSTER_SIZE as u32 + 1) >> 1;\npub(crate) const QUORUM_BITSET_ENTRY: u32 = 1024; // must be 2^t\n\npub(crate) const PAXOS_PORT: u16 = 12345;\npub(crate) const MAGIC_BITS: [u8; MAGIC_LEN] = [0x18, 0x03, 0x05, 0x20];\n\n#[derive(Debug, PartialEq, Eq, Clone, Copy)]\n#[repr(C)]\npub(crate) enum ReplicaStatus {\n    STATUS_NORMAL = 0,\n    STATUS_VIEW_CHANGE,\n    STATUS_RECOVERING,\n}\n\n#[derive(Debug, PartialEq, Eq)]\n#[repr(C)]\npub(crate) enum FastProgXdp {\n    FAILED = -1,\n    FAST_PROG_XDP_HANDLE_PREPARE = 0,\n    FAST_PROG_XDP_HANDLE_REQUEST,\n    FAST_PROG_XDP_HANDLE_PREPAREOK,\n    FAST_PROG_XDP_WRITE_BUFFER,\n    FAST_PROG_XDP_PREPARE_REPLY,\n    FAST_PROG_XDP_MAX,\n}\n\n#[derive(Debug, PartialEq, Eq)]\n#[repr(C)]\npub(crate) enum FastProgTc {\n    FAST_PROG_TC_BROADCAST = 0,\n    FAST_PROG_TC_MAX,\n}\n\n#[repr(C)]\n#[derive(Clone, Copy)]\npub(crate) struct PaxosConfigure {\n    pub(crate) addr: u32, // ipv4.\n    pub(crate) port: u16,\n    pub(crate) eth: [u8; ETH_ALEN],\n}\n"
  },
  {
    "path": "samples/electrode/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n#![allow(non_camel_case_types)]\n#![allow(non_snake_case)]\n\nextern crate rex;\n\nuse core::mem::{size_of, swap};\n\nuse rex::sched_cls::*;\nuse rex::utils::*;\nuse rex::xdp::*;\nuse rex::{read_field, rex_printk, rex_tc, rex_xdp};\n\npub mod common;\npub mod maps;\n\nuse common::*;\nuse maps::*;\n\nmacro_rules! swap_field {\n    ($field1:expr, $field2:expr, $size:ident) => {\n        for i in 0..$size {\n            swap(&mut $field1[i], &mut $field2[i])\n        }\n    };\n}\n\n// NOTE: function calls are not allowed while holding a lock....\n// Cause Paxos is in fact a serialized protocol, we limit our to one-core, then\n// no lock is needed.\n\n#[rex_xdp]\nfn fast_paxos_main(obj: &xdp, ctx: &mut xdp_md) -> Result {\n    let header_len =\n        size_of::<ethhdr>() + size_of::<iphdr>() + size_of::<udphdr>();\n    let iphdr_base = size_of::<ethhdr>();\n    let iphdr_end = iphdr_base + size_of::<iphdr>();\n\n    match u8::from_be(read_field!(\n        ctx.data_slice,\n        iphdr_base,\n        iphdr,\n        protocol,\n        u8\n    )) as u32\n    {\n        IPPROTO_TCP => {\n            // NOTE: currently we only take care of UDP memcached\n        }\n        IPPROTO_UDP => {\n            let port = u16::from_be(read_field!(\n                ctx.data_slice,\n                iphdr_end,\n                udphdr,\n                dest,\n                u16\n            ));\n\n            let payload = &mut ctx.data_slice[header_len..];\n\n            // port check, our process bound to 12345.\n            // don't have magic bits...\n            if port != PAXOS_PORT ||\n                payload.len() < MAGIC_LEN + size_of::<u64>() ||\n                !payload.starts_with(&MAGIC_BITS)\n            {\n                return Ok(XDP_PASS as i32);\n            }\n\n            // check the message type\n            return handle_udp_fast_paxos(obj, ctx);\n        }\n        _ => {}\n    };\n\n    Ok(XDP_PASS as i32)\n}\n\n#[rex_tc]\nfn fast_broad_cast_main(obj: &sched_cls, skb: &mut __sk_buff) -> Result {\n    let header_len =\n        size_of::<iphdr>() + size_of::<ethhdr>() + size_of::<udphdr>();\n    let iphdr_base = size_of::<ethhdr>();\n    let iphdr_end = iphdr_base + size_of::<iphdr>();\n\n    // check if the packet is long enough\n    if skb.data_slice.len() <= header_len {\n        return Ok(TC_ACT_OK as i32);\n    }\n\n    if u8::from_be(read_field!(skb.data_slice, iphdr_base, iphdr, protocol, u8))\n        as u32 ==\n        IPPROTO_UDP\n    {\n        let port = u16::from_be(read_field!(\n            skb.data_slice,\n            iphdr_end,\n            udphdr,\n            dest,\n            u16\n        ));\n\n        let payload = &skb.data_slice[header_len..];\n        // check for the magic bits and Paxos port\n        // only port 12345 is allowed\n        if port != PAXOS_PORT ||\n            payload.len() < MAGIC_LEN + size_of::<u64>() ||\n            !payload.starts_with(&MAGIC_BITS)\n        {\n            return Ok(TC_ACT_OK as i32);\n        }\n\n        return handle_udp_fast_broad_cast(obj, skb);\n    }\n\n    Ok(TC_ACT_OK as i32)\n}\n\n#[inline(always)]\nfn handle_udp_fast_broad_cast(obj: &sched_cls, skb: &mut __sk_buff) -> Result {\n    let header_len = size_of::<ethhdr>() +\n        size_of::<iphdr>() +\n        size_of::<udphdr>() +\n        MAGIC_LEN;\n    let payload = &skb.data_slice[header_len..];\n\n    let (type_len_bytes, payload) = payload.split_at(size_of::<u64>());\n    let type_str_len = header_len + size_of::<u64>();\n    let type_len = u64::from_ne_bytes(type_len_bytes.try_into().unwrap());\n    let len = payload.len();\n\n    if type_len >= MTU || len < type_len as usize || len < 5 {\n        rex_printk!(\"too small type_len: {}\\n\", type_len).ok();\n        return Ok(TC_ACT_SHOT as i32);\n    }\n\n    rex_printk!(\"handle_udp_fast_broad_cast\\n\").ok();\n\n    // update payload index\n    let payload = &payload[type_len as usize..];\n    if payload.len() < FAST_PAXOS_DATA_LEN {\n        return Ok(TC_ACT_SHOT as i32);\n    }\n\n    let msg_view = u32::from_ne_bytes(payload[0..4].try_into().unwrap());\n    let is_broadcast = msg_view & BROADCAST_SIGN_BIT;\n    let msg_view = msg_view ^ BROADCAST_SIGN_BIT;\n\n    let msg_last_op = u32::from_ne_bytes(payload[4..8].try_into().unwrap());\n    let message_type = compute_message_type(payload);\n\n    if message_type == FastProgXdp::FAST_PROG_XDP_HANDLE_PREPARE {\n        let idx = msg_last_op & (QUORUM_BITSET_ENTRY - 1);\n        let entry = obj.bpf_map_lookup_elem(&map_quorum, &idx).ok_or(0i32)?;\n        if entry.view != msg_view || entry.opnum != msg_last_op {\n            entry.view = msg_view;\n            entry.opnum = msg_last_op;\n            entry.bitset = 0;\n        }\n    }\n\n    if is_broadcast == 0 {\n        return Ok(TC_ACT_OK as i32);\n    };\n\n    let zero = 0u32;\n    let ctr_state =\n        obj.bpf_map_lookup_elem(&map_ctr_state, &zero).ok_or(0i32)?;\n\n    let mut id = 0u8;\n    let mut nxt;\n\n    {\n        let type_str = &mut skb.data_slice[type_str_len..];\n        if type_str.starts_with(b\"sp\") {\n            if ctr_state.leader_idx == 0 {\n                id = 1;\n            }\n            nxt = id + 1;\n            if ctr_state.leader_idx == nxt as u32 {\n                nxt += 1;\n            }\n\n            type_str[0] = nxt;\n            type_str[1] = b'M';\n            if nxt < CLUSTER_SIZE {\n                obj.bpf_clone_redirect(skb, skb.ifindex(), 0).unwrap();\n            }\n        } else {\n            id = type_str[0];\n            nxt = id + 1;\n            if ctr_state.leader_idx == nxt as u32 {\n                nxt += 1;\n            }\n            type_str[0] = nxt;\n\n            if nxt < CLUSTER_SIZE {\n                obj.bpf_clone_redirect(skb, skb.ifindex(), 0).unwrap();\n            }\n        }\n    }\n\n    // our version bpf_clone_redirect will update the data reference.\n    let type_str = &mut skb.data_slice[type_str_len..];\n    type_str[0] = b's';\n    type_str[1] = b'p';\n\n    let key = id as u32;\n    let replica_info = obj\n        .bpf_map_lookup_elem(&map_configure, &key)\n        .ok_or(TC_ACT_SHOT as i32)?;\n\n    {\n        let udp_header = &mut obj.udp_header(skb);\n        udp_header.dest = replica_info.port;\n        udp_header.check = 0;\n    }\n\n    {\n        let ip_header = &mut obj.ip_header(skb);\n        *ip_header.daddr() = replica_info.addr;\n        ip_header.check = compute_ip_checksum(ip_header);\n    }\n\n    let mut eth_header = obj.eth_header(skb);\n    for i in 0..ETH_ALEN {\n        eth_header.h_dest[i] = replica_info.eth[i];\n    }\n\n    Ok(TC_ACT_OK as i32)\n}\n\n#[inline(always)]\nfn handle_udp_fast_paxos(obj: &xdp, ctx: &mut xdp_md) -> Result {\n    let header_len =\n        size_of::<ethhdr>() + size_of::<iphdr>() + size_of::<udphdr>();\n    let payload = &mut ctx.data_slice[header_len + MAGIC_LEN..];\n\n    let type_len_bytes = &payload[..size_of::<u64>()];\n    let type_len = u64::from_ne_bytes(type_len_bytes.try_into().unwrap());\n    rex_printk!(\"type_len: {}\\n\", type_len).ok();\n\n    // Check the conditions\n    let len = payload.len();\n    if type_len >= MTU || len < type_len as usize {\n        rex_printk!(\"too big type_len: {}\\n\", type_len).ok();\n        return Ok(XDP_PASS as i32);\n    }\n    let payload_index = header_len + MAGIC_LEN + size_of::<u64>();\n    let payload = &mut ctx.data_slice[payload_index..];\n\n    #[cfg(feature = \"fast_reply\")]\n    {\n        // PrepareMessage in `vr`.\n        if len > PREPARE_TYPE_LEN &&\n            payload[10..12].starts_with(b\"vr\") &&\n            payload[19..27].starts_with(b\"PrepareM\")\n        {\n            let payload_index = payload_index + PREPARE_TYPE_LEN;\n            return handle_prepare(obj, ctx, payload_index);\n        }\n    }\n\n    #[cfg(feature = \"fast_quorum_prune\")]\n    {\n        // PrepareOK message in `vr`.\n        if len > PREPAREOK_TYPE_LEN &&\n            payload[10..12].starts_with(b\"vr\") &&\n            payload[19..27].starts_with(b\"PrepareO\")\n        {\n            return handle_prepare_ok(obj, ctx, payload_index);\n        }\n\n        if len > MYPREPAREOK_TYPE_LEN &&\n            payload[10..12].starts_with(b\"vr\") &&\n            payload[13..17].starts_with(b\"MyPr\")\n        {\n            return handle_prepare_ok(obj, ctx, payload_index);\n        }\n    }\n\n    Ok(XDP_PASS as i32)\n}\n\n#[inline(always)]\nfn compute_message_type(payload: &[u8]) -> FastProgXdp {\n    let len = payload.len();\n\n    // if not a valid message, return FAILED\n    if len < 13 || !payload[10..12].starts_with(b\"vr\") {\n        return FastProgXdp::FAILED;\n    }\n\n    // check the message type\n    if len > PREPARE_TYPE_LEN && payload[19..27].starts_with(b\"PrepareM\") {\n        return FastProgXdp::FAST_PROG_XDP_HANDLE_PREPARE;\n    } else if len > REQUEST_TYPE_LEN && payload[19..27].starts_with(b\"RequestM\")\n    {\n        return FastProgXdp::FAST_PROG_XDP_HANDLE_REQUEST;\n    } else if len > PREPAREOK_TYPE_LEN &&\n        payload[19..27].starts_with(b\"PrepareO\")\n    {\n        return FastProgXdp::FAST_PROG_XDP_HANDLE_PREPAREOK;\n    } else if len > MYPREPAREOK_TYPE_LEN && payload[13..17].starts_with(b\"MyPr\")\n    {\n        return FastProgXdp::FAST_PROG_XDP_HANDLE_PREPAREOK;\n    }\n\n    FastProgXdp::FAILED\n}\n\n// This function is ignored in the original implementation.\n// #[inline(always)]\n// fn handle_request(_obj: &xdp, _ctx: &mut xdp_md) -> Result {\n//     Ok(XDP_PASS as i32)\n// }\n\n#[inline(always)]\nfn handle_prepare(obj: &xdp, ctx: &mut xdp_md, payload_index: usize) -> Result {\n    // payload_index = header_len + MAGIC_LEN + size_of::<u64>() +\n    // PREPARE_TYPE_LEN point to extra data\n    let payload = &mut ctx.data_slice[payload_index..];\n\n    // check the message len\n    if payload.len() < FAST_PAXOS_DATA_LEN {\n        return Ok(XDP_PASS as i32);\n    }\n\n    // NOTE: may update to struct later\n    let msg_view = u32::from_ne_bytes(payload[0..4].try_into().unwrap()) as u64;\n    let msg_last_op =\n        u32::from_ne_bytes(payload[4..8].try_into().unwrap()) as u64;\n    let msg_batch_start =\n        u32::from_ne_bytes(payload[8..12].try_into().unwrap()) as u64;\n\n    let zero = 0u32;\n    let ctr_state =\n        obj.bpf_map_lookup_elem(&map_ctr_state, &zero).ok_or(0i32)?;\n\n    rex_printk!(\"handle_prepare\\n\").ok();\n    // rare case, not handled properly now.\n    if ctr_state.state != ReplicaStatus::STATUS_NORMAL {\n        return Ok(XDP_DROP as i32);\n    }\n\n    if msg_view < ctr_state.view {\n        return Ok(XDP_DROP as i32);\n    }\n\n    if msg_view > ctr_state.view {\n        return Ok(XDP_PASS as i32);\n    }\n\n    // Resend the prepareOK message\n    if msg_last_op <= ctr_state.last_op {\n        return prepare_fast_reply(obj, ctx, payload_index);\n    }\n\n    // rare case, to user-space.\n    if msg_batch_start > ctr_state.last_op + 1 {\n        return Ok(XDP_PASS as i32);\n    }\n\n    ctr_state.last_op = msg_last_op;\n    write_buffer(obj, ctx, payload_index)\n}\n\n#[inline(always)]\nfn write_buffer(obj: &xdp, ctx: &mut xdp_md, payload_index: usize) -> Result {\n    // payload_index = header_len + MAGIC_LEN + size_of::<u64>() +\n    // PREPARE_TYPE_LEN check the end of the payload\n    if ctx.data_slice.len() < payload_index + FAST_PAXOS_DATA_LEN {\n        return Ok(XDP_PASS as i32);\n    }\n\n    rex_printk!(\"write buffer\\n\").ok();\n\n    let payload = &mut ctx.data_slice[payload_index + FAST_PAXOS_DATA_LEN..];\n\n    if payload.len() < MAX_DATA_LEN {\n        return Ok(XDP_PASS as i32);\n    }\n\n    // buffer not enough, offload to user-space.\n    // It's easy to avoid cause VR sends `CommitMessage` make followers keep up\n    // with the leader.\n    let mut pt = map_prepare_buffer.reserve(MAX_DATA_LEN).ok_or(0i32)?;\n\n    pt.copy_from_slice(&payload[0..MAX_DATA_LEN]);\n    pt.submit(0); // guaranteed to succeed.\n\n    prepare_fast_reply(obj, ctx, payload_index)\n}\n\n#[inline(always)]\nfn prepare_fast_reply(\n    obj: &xdp,\n    ctx: &mut xdp_md,\n    payload_index: usize,\n) -> Result {\n    let mut payload = &mut ctx.data_slice[payload_index..];\n\n    if payload.len() <= FAST_PAXOS_DATA_LEN + size_of::<u64>() {\n        return Ok(XDP_PASS as i32);\n    }\n\n    rex_printk!(\"prepare_fast_reply\\n\").ok();\n\n    // read our state\n    // may update to function parameter later\n    let zero = 0u32;\n    let ctr_state =\n        obj.bpf_map_lookup_elem(&map_ctr_state, &zero).ok_or(0i32)?;\n\n    // struct paxos_configure *leaderInfo =\n    // bpf_map_lookup_elem(&map_configure, &ctr_state->leaderIdx);\n    let leader_info = obj\n        .bpf_map_lookup_elem(&map_configure, &ctr_state.leader_idx)\n        .ok_or(0i32)?;\n\n    // Write NONFRAG_MAGIC to the start of the payload\n    // FIX: need to check to_ne_bytes or to_be_bytes\n    payload[0..4].copy_from_slice(&NONFRAG_MAGIC.to_ne_bytes());\n    payload = &mut payload[4..];\n    // Write MYPREPAREOK_TYPE_LEN to the new start of the payload\n    payload[0..8].copy_from_slice(&MYPREPAREOK_TYPE_LEN.to_ne_bytes());\n    payload = &mut payload[8..];\n\n    // change \"specpaxos.vr.proto.PrepareMessage\" to \"specpaxos.vr.MyPrepareOK\"\n    let replacement: &[u8] = b\"MyPrepareOK\";\n    for (i, &byte) in replacement.iter().enumerate() {\n        payload[13 + i] = byte;\n    }\n    // Move the slice start by MYPREPAREOK_TYPE_LEN\n    payload = &mut payload[MYPREPAREOK_TYPE_LEN..];\n\n    // Write the view number, last_op and my_idx to the payload\n    payload[0..4].copy_from_slice(&(ctr_state.view as u32).to_ne_bytes());\n    payload[4..8].copy_from_slice(&(payload_index as u32).to_ne_bytes());\n    payload[8..12].copy_from_slice(&ctr_state.my_idx.to_ne_bytes());\n    // Move the slice start by FAST_PAXOS_DATA_LEN\n    payload = &mut payload[FAST_PAXOS_DATA_LEN..];\n\n    if payload.len() < (size_of::<u64>() * 3 + size_of::<u32>()) {\n        return Ok(XDP_PASS as i32);\n    }\n\n    let size = (size_of::<u64>() * 2 + size_of::<u32>()) as u64;\n    // write the len in the protocal, last_op and my_idx to the payload\n    payload[0..8].copy_from_slice(&size.to_ne_bytes());\n    payload[8..16].copy_from_slice(&ctr_state.view.to_ne_bytes());\n    payload[16..24].copy_from_slice(&(payload_index as u64).to_ne_bytes());\n    // Write ctr_state.my_idx\n    payload[24..28].copy_from_slice(&ctr_state.my_idx.to_ne_bytes());\n    // move the slice start by size_of::<u64>() * 3 + size_of::<u32>()\n    let size = (size_of::<u64>() * 3 + size_of::<u32>()) as u64;\n    payload = &mut payload[size as usize..];\n\n    let useless_len = payload.len() as u16;\n    let new_len = ctx.data_length() as u16 - useless_len;\n\n    {\n        let eth_header: &mut ethhdr = &mut obj.eth_header(ctx);\n        swap_field!(eth_header.h_dest, eth_header.h_source, ETH_ALEN);\n    }\n    {\n        // update the port\n        let udp_header = &mut obj.udp_header(ctx);\n        udp_header.source = udp_header.dest;\n        udp_header.dest = leader_info.port;\n        udp_header.check = 0;\n        udp_header.len = new_len.to_be();\n    }\n\n    {\n        let ip_header = &mut obj.ip_header(ctx);\n        ip_header.tot_len = (new_len + size_of::<iphdr>() as u16).to_be();\n        *ip_header.saddr() = *ip_header.daddr();\n        *ip_header.daddr() = leader_info.addr;\n        ip_header.check = compute_ip_checksum(ip_header);\n    }\n\n    // FIX: need to consider the positive offset\n    // but the original code check the length before adjust the tail\n    if obj\n        .bpf_xdp_adjust_tail(ctx, new_len as i32 - ctx.data_length() as i32)\n        .is_err()\n    {\n        rex_printk!(\"adjust tail failed\\n\").ok();\n        return Ok(XDP_DROP as i32);\n    }\n\n    Ok(XDP_TX as i32)\n}\n\n#[inline(always)]\nfn handle_prepare_ok(\n    obj: &xdp,\n    ctx: &mut xdp_md,\n    payload_index: usize,\n) -> Result {\n    // payload_index = header_len + MAGIC_LEN + size_of::<u64>()\n    let payload = &mut ctx.data_slice[payload_index..];\n    let len = payload.len();\n\n    if len <= FAST_PAXOS_DATA_LEN {\n        return Ok(XDP_DROP as i32);\n    }\n\n    rex_printk!(\"handle prepareOK\\n\").ok();\n\n    let msg_view = u32::from_ne_bytes(payload[0..4].try_into().unwrap());\n    let msg_opnum = u32::from_ne_bytes(payload[4..8].try_into().unwrap());\n    let msg_replica_idx =\n        u32::from_ne_bytes(payload[8..12].try_into().unwrap());\n    let idx = msg_opnum & (QUORUM_BITSET_ENTRY - 1);\n\n    let entry = obj.bpf_map_lookup_elem(&map_quorum, &idx).ok_or(0i32)?;\n\n    if entry.view != msg_view || entry.opnum != msg_opnum {\n        return Ok(XDP_PASS as i32);\n    }\n\n    entry.bitset |= 1 << msg_replica_idx;\n\n    if entry.bitset.count_ones() != QUORUM_SIZE - 1 {\n        return Ok(XDP_DROP as i32);\n    }\n\n    // *context = (void *)payload + typeLen - data;\n    if obj\n        .bpf_xdp_adjust_tail(ctx, -(payload_index as i32))\n        .is_err()\n    {\n        rex_printk!(\"adjust tail failed\\n\").ok();\n        return Ok(XDP_DROP as i32);\n    }\n\n    Ok(XDP_PASS as i32)\n}\n"
  },
  {
    "path": "samples/electrode/src/maps.rs",
    "content": "use rex::linux::bpf::bpf_spin_lock;\nuse rex::map::*;\nuse rex::rex_map;\n\nuse crate::common::*;\n\n#[repr(C)]\n#[derive(Clone, Copy)]\npub(crate) struct paxos_quorum {\n    pub(crate) view: u32,\n    pub(crate) opnum: u32,\n    pub(crate) bitset: u32,\n}\n\n#[repr(C)]\n#[derive(Clone, Copy)]\npub(crate) struct paxos_ctr_state {\n    pub(crate) state: ReplicaStatus,\n    pub(crate) my_idx: u32,\n    pub(crate) leader_idx: u32,\n    pub(crate) batch_size: u32,\n    pub(crate) view: u64,\n    pub(crate) last_op: u64,\n}\n\n#[repr(C)]\n#[derive(Clone, Copy)]\npub(crate) struct paxos_batch {\n    counter: u32,\n    lock: bpf_spin_lock,\n}\n\n#[rex_map]\npub(crate) static map_configure: RexArrayMap<PaxosConfigure> =\n    RexArrayMap::new(FAST_REPLICA_MAX, 0);\n\n#[rex_map]\npub(crate) static map_ctr_state: RexArrayMap<paxos_ctr_state> =\n    RexArrayMap::new(1, 0);\n\n#[rex_map]\npub(crate) static map_msg_last_op: RexArrayMap<u64> = RexArrayMap::new(1, 0);\n\n#[rex_map]\npub(crate) static map_quorum: RexArrayMap<paxos_quorum> =\n    RexArrayMap::new(QUORUM_BITSET_ENTRY, 0);\n\n#[rex_map]\npub(crate) static batch_context: RexArrayMap<paxos_batch> =\n    RexArrayMap::new(1, 0);\n\n#[rex_map]\npub(crate) static map_prepare_buffer: RexRingBuf = RexRingBuf::new(1 << 20, 0);\n#[rex_map]\npub(crate) static map_request_buffer: RexRingBuf = RexRingBuf::new(1 << 20, 0);\n"
  },
  {
    "path": "samples/error_injector/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/error_injector/.gitignore",
    "content": "target\nuserapp\n"
  },
  {
    "path": "samples/error_injector/Cargo.toml",
    "content": "[package]\nname = \"error_injector\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/error_injector/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/error_injector/loader.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/wait.h>\n#include <unistd.h>\n\n#include <librex.h>\n#include <bpf/libbpf.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/error_injector\"\n\n#define USAGE \"./loader <syscall> <errno>\\n\"\n\nint main(int argc, char *argv[])\n{\n\tstruct bpf_object *obj;\n\tstruct bpf_program *prog;\n\tstruct bpf_link *link = NULL;\n\tstruct bpf_map *pid_to_errno;\n\tstruct rex_obj *rex_obj;\n\tunsigned long errno_to_inject;\n\tint pid;\n\tLIBBPF_OPTS(bpf_ksyscall_opts, opts);\n\n\tif (argc < 3) {\n\t\tfprintf(stderr, USAGE);\n\t\treturn 1;\n\t}\n\n\terrno_to_inject = -strtoul(argv[2], NULL, 10);\n\n\trex_obj = rex_obj_load(EXE);\n\tif (!rex_obj) {\n\t\tfprintf(stderr, \"rex_obj_load failed\\n\");\n\t\treturn 1;\n\t}\n\n\tobj = rex_obj_get_bpf(rex_obj);\n\tif (!obj) {\n\t\tfprintf(stderr, \"rex_obj_get_bpf failed\\n\");\n\t\treturn 1;\n\t}\n\n\tprog = bpf_object__find_program_by_name(obj, \"err_injector\");\n\tif (!prog) {\n\t\tfprintf(stderr, \"bpf_object__find_program_by_name failed\\n\");\n\t\treturn 1;\n\t}\n\n\topts.retprobe = 0;\n\tlink = bpf_program__attach_ksyscall(prog, argv[1], &opts);\n\tif (libbpf_get_error(link)) {\n\t\tfprintf(stderr, \"ERROR: bpf_program__attach failed\\n\");\n\t\tlink = NULL;\n\t\treturn 1;\n\t}\n\n\tpid_to_errno = bpf_object__find_map_by_name(obj, \"pid_to_errno\");\n\tif (libbpf_get_error(pid_to_errno)) {\n\t\tfprintf(stderr, \"ERROR: Could not find map: pid_map\\n\");\n\t\tgoto cleanup;\n\t}\n\n\tpid = fork();\n\n\tif (pid < 0) {\n\t\tperror(\"fork\");\n\t} else if (!pid) {\n\t\tpid = getpid();\n\t\tif (bpf_map__update_elem(\n\t\t\t    pid_to_errno, &pid, sizeof(pid), &errno_to_inject,\n\t\t\t    sizeof(errno_to_inject), BPF_ANY) < 0) {\n\t\t\tfprintf(stderr, \"ERROR: updating pid_map failed\\n\");\n\t\t}\n\n\t\tbpf_link__destroy(link);\n\n\t\texecl(\"./userapp\", \"./userapp\", NULL);\n\t\tperror(\"executing userapp failed\");\n\t\treturn 1;\n\t}\n\n\twait(NULL);\n\ncleanup:\n\tbpf_link__destroy(link);\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/error_injector/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nerror_injector_clippy = custom_target(\n  'error_injector-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nerror_injector_build = custom_target(\n  'error_injector-build',\n  output: ['error_injector'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: error_injector_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nerror_injector_loader = executable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\nerror_injector_userapp = executable(\n  'userapp',\n  'userapp.c',\n  build_by_default: true,\n  dependencies: [kernel_dep],\n  pie: true\n)\n\nsanity_test = custom_target(\n  'sanity_test',\n  output: ['runtest.py'],\n  input: join_paths(meson.current_source_dir(), 'tests/runtest.py'),\n  command: [\n    'cp', '@INPUT@', '@OUTPUT@',\n    ]\n )\n\nruntest_deps += [error_injector_build, error_injector_loader, error_injector_userapp, sanity_test]\n\nsanity_test_env = environment()\nsanity_test_env.set('SAMPLE_PATH', meson.current_build_dir())\nsanity_test_env.set('Q_SCRIPT',\n  join_paths(meson.project_source_root(), 'scripts/q-script/sanity-test-q')\n)\nsanity_test_env.set('KERNEL_PATH', kbuild_dir)\n\ntest('error_injector',\n  python3_bin,\n  args: [sanity_test_scripts],\n  env: sanity_test_env,\n  depends: runtest_deps,\n  is_parallel: false,\n  workdir: meson.current_build_dir()\n)\n"
  },
  {
    "path": "samples/error_injector/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n\nuse rex::kprobe::kprobe;\nuse rex::map::RexHashMap;\nuse rex::pt_regs::PtRegs;\nuse rex::{Result, rex_kprobe, rex_map};\n\n#[allow(non_upper_case_globals)]\n#[rex_map]\nstatic pid_to_errno: RexHashMap<i32, u64> = RexHashMap::new(1, 0);\n\n#[rex_kprobe]\npub fn err_injector(obj: &kprobe, ctx: &mut PtRegs) -> Result {\n    obj.bpf_get_current_task()\n        .map(|t| t.get_pid())\n        .and_then(|p| obj.bpf_map_lookup_elem(&pid_to_errno, &p).cloned())\n        .map(|e| obj.bpf_override_return(ctx, e))\n        .ok_or(0)\n}\n"
  },
  {
    "path": "samples/error_injector/tests/runtest.py",
    "content": "#!/usr/bin/env python\n\n\nimport re\nimport subprocess\nfrom time import sleep\n\nprocess = 0\n\n\ndef count_bpf_programs():\n    try:\n        # Run bpftool to list all loaded BPF programs\n        result = subprocess.run(\n            \"bpftool prog show\",\n            capture_output=True,\n            shell=True,\n            text=True,\n        )\n\n        # Process the output to count programs\n        if result.stdout:\n            # Each program details start on a new line\n            output = result.stdout.strip().split(\"\\n\")\n            programs = [line for line in output if \"name\" in line]\n            return len(programs)\n        else:\n            return 0\n    except FileNotFoundError:\n        print(\"bpftool is not installed or not found in the PATH.\")\n        return 0\n    except Exception as e:\n        print(f\"An error occurred: {e}\")\n        return 0\n\n\ndef run_loader():\n    global process\n    process = subprocess.Popen(\n        [\"./loader\", \"dup\", \"22\"],\n        text=True,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n    )\n\n\ndef capture_output() -> bool:\n    try:\n        global process\n\n        sleep(2)\n        process.kill()\n        std_out, std_err = process.communicate(timeout=7)\n        prog_match = re.findall(r\"dup: Invalid argument\", std_err, re.M)\n        if len(prog_match) == 1:\n            print(\"Success\")\n            return True\n        else:\n            print(\"Failed\")\n            return False\n\n    except subprocess.CalledProcessError:\n        return False\n    except subprocess.TimeoutExpired:\n        process.kill()\n        return False\n\n\ndef main():\n\n    old_prog_num = count_bpf_programs()\n    run_loader()\n    count = 0\n    while old_prog_num == count_bpf_programs():\n        sleep(1)\n        count += 1\n        if count == 5:\n            break\n    grade_file = open(\"auto_grade.txt\", \"w\")\n    if capture_output():\n        grade_file.write(\"success\")\n    else:\n        grade_file.write(\"fail\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "samples/error_injector/userapp.c",
    "content": "#define _DEFAULT_SOURCE\n#include <stdio.h>\n#include <unistd.h>\n#include <linux/unistd.h>\n\nint main(void)\n{\n\tif (syscall(__NR_dup, 0) < 0) {\n\t\tperror(\"dup\");\n\t}\n}\n"
  },
  {
    "path": "samples/hello/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/hello/.gitignore",
    "content": "target\n"
  },
  {
    "path": "samples/hello/Cargo.toml",
    "content": "[package]\nname = \"hello\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/hello/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/hello/event-trigger.c",
    "content": "#include <unistd.h>\n#include <linux/unistd.h>\n\nint main(void)\n{\n\treturn syscall(__NR_dup, 1);\n}\n"
  },
  {
    "path": "samples/hello/loader.c",
    "content": "#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\n#include <linux/perf_event.h>\n#include <linux/unistd.h>\n\n#include <librex.h>\n#include <bpf/libbpf.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/hello\"\n\nint main(void)\n{\n\tint trace_pipe_fd;\n\tstruct bpf_object *obj;\n\tstruct bpf_program *prog;\n\tstruct bpf_link *link = NULL;\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\tprog = bpf_object__find_program_by_name(obj, \"rex_prog1\");\n\tif (!prog) {\n\t\tfprintf(stderr, \"_start not found\\n\");\n\t\treturn 1;\n\t}\n\n\tlink = bpf_program__attach(prog);\n\tif (libbpf_get_error(link)) {\n\t\tfprintf(stderr, \"ERROR: bpf_program__attach failed\\n\");\n\t\tlink = NULL;\n\t\treturn 1;\n\t}\n\n\ttrace_pipe_fd = openat(AT_FDCWD, \"/sys/kernel/debug/tracing/trace_pipe\",\n\t\t\t       O_RDONLY);\n\n\tfor (;;) {\n\t\tchar c;\n\t\tfflush(stdout);\n\t\tif (read(trace_pipe_fd, &c, 1) == 1)\n\t\t\tputchar(c);\n\t}\n\n\tbpf_link__destroy(link);\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/hello/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nhello_clippy = custom_target(\n  'hello-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nhello_build = custom_target(\n  'hello-build',\n  output: ['hello'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nhello_loader = executable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\nhello_trigger = executable(\n  'event-trigger',\n  'event-trigger.c',\n  build_by_default: true,\n  dependencies: [kernel_dep],\n  pie: true\n)\n\nsanity_test = custom_target(\n  'sanity_test',\n  output: ['runtest.py'],\n  input: join_paths(meson.current_source_dir(), 'tests/runtest.py'),\n  command: [\n    'cp', '@INPUT@', '@OUTPUT@',\n    ]\n )\n\nruntest_deps += [hello_build, hello_loader, hello_trigger, sanity_test]\n\nsanity_test_env = environment()\nsanity_test_env.set('SAMPLE_PATH', meson.current_build_dir())\nsanity_test_env.set('Q_SCRIPT',\n  join_paths(meson.project_source_root(), 'scripts/q-script/sanity-test-q')\n)\nsanity_test_env.set('KERNEL_PATH', kbuild_dir)\n\ntest('hello_test', \n  python3_bin, \n  args: [sanity_test_scripts],\n  env: sanity_test_env,\n  depends: runtest_deps,\n  is_parallel: false,\n  workdir: meson.current_build_dir()\n)\n"
  },
  {
    "path": "samples/hello/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/hello/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n\nextern crate rex;\n\nuse rex::tracepoint::*;\nuse rex::{Result, rex_printk, rex_tracepoint};\n\n#[rex_tracepoint]\nfn rex_prog1(\n    obj: &tracepoint<SyscallsEnterDupCtx>,\n    _: &'static SyscallsEnterDupCtx,\n) -> Result {\n    let option_task = obj.bpf_get_current_task();\n    if let Some(task) = option_task {\n        let cpu = obj.bpf_get_smp_processor_id();\n        let pid = task.get_pid();\n        rex_printk!(\"Rust triggered from PID {} on CPU {}.\\n\", pid, cpu)?;\n    }\n    Ok(0)\n}\n"
  },
  {
    "path": "samples/hello/tests/runtest.py",
    "content": "#!/bin/python\n\nimport re\nimport subprocess\nfrom time import sleep\n\nprocess = 0\n\n\ndef count_bpf_programs():\n    try:\n        # Run bpftool to list all loaded BPF programs\n        result = subprocess.run(\n            \"bpftool prog show\",\n            capture_output=True,\n            shell=True,\n            text=True,\n        )\n\n        # Process the output to count programs\n        if result.stdout:\n            # Each program details start on a new line\n            output = result.stdout.strip().split(\"\\n\")\n            programs = [line for line in output if \"name\" in line]\n            return len(programs)\n        else:\n            return 0\n    except FileNotFoundError:\n        print(\"bpftool is not installed or not found in the PATH.\")\n        return 0\n    except Exception as e:\n        print(f\"An error occurred: {e}\")\n        return 0\n\n\ndef run_loader():\n    global process\n    process = subprocess.Popen(\n        [\"./loader\"],\n        text=True,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n    )\n\n\ndef trigger_prog():\n    try:\n        subprocess.run(\"./event-trigger\", shell=True)\n    except subprocess.CalledProcessError:\n        print(\"CalledProcessError\")\n\n\ndef capture_output() -> bool:\n    try:\n        global process\n        trigger_prog()\n        trigger_prog()\n\n        sleep(2)\n        process.kill()\n        std_out, std_err = process.communicate(timeout=7)\n        re_match = re.findall(\n            r\"Rust triggered from PID \\d+ on CPU .+\", std_out, re.M\n        )\n        if len(re_match) == 2:\n            print(\"Success\")\n            return True\n        else:\n            print(\"Failed\")\n            return False\n\n    except subprocess.CalledProcessError:\n        return False\n    except subprocess.TimeoutExpired:\n        process.kill()\n        return False\n\n\ndef main():\n\n    old_prog_num = count_bpf_programs()\n    run_loader()\n    count = 0\n    while old_prog_num == count_bpf_programs():\n        sleep(1)\n        count += 1\n        if count == 5:\n            break\n    grade_file = open(\"auto_grade.txt\", \"w\")\n    if capture_output():\n        grade_file.write(\"success\")\n    else:\n        grade_file.write(\"fail\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "samples/map_bench/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/map_bench/Cargo.toml",
    "content": "[package]\nname = \"map_bench\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/map_bench/bench.sh",
    "content": "#!/usr/bin/env bash\n\nif [ \"$#\" -ne 2 ]; then\n\techo \"Usage: $0 <rex|bpf> <atomic|hash|array>\"\n\texit 1\nfi\n\nmkdir output\necho 8192 > /sys/kernel/debug/tracing/buffer_size_kb\n\nif [[ \"$1\" == \"rex\" ]]; then\n\t./event-trigger 6000 1\n\tcat /sys/kernel/debug/tracing/trace | tail -5000 >\"./output/rex_${2}.txt\"\nelif [[ \"$1\" == \"bpf\" ]]; then\n\t./event-trigger 6000 1\n\tcat /sys/kernel/debug/tracing/trace | tail -5000 >\"./output/bpf_${2}.txt\"\nfi\n\n\n# clean buffer\necho >/sys/kernel/debug/tracing/trace\n\n# unlink\nrm -rf /sys/fs/bpf/*\n"
  },
  {
    "path": "samples/map_bench/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/map_bench/event-trigger.c",
    "content": "#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\nint main(int argc, char *argv[])\n{\n\tint nr_rounds, arg, fd;\n\n\tif (argc != 3)\n\t\tasm volatile(\"ud2\");\n\n\tnr_rounds = atoi(argv[1]);\n\targ = atoi(argv[2]);\n\tfd = open(\"/proc/kprobe_target\", O_RDONLY);\n\tif (fd < 0) {\n\t\tperror(\"open\");\n\t\treturn 1;\n\t}\n\n\tfor (int i = 0; i < nr_rounds; i++)\n\t\tioctl(fd, 1313, arg);\n\n\tclose(fd);\n}\n"
  },
  {
    "path": "samples/map_bench/loader.c",
    "content": "#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\n#include <linux/perf_event.h>\n#include <linux/unistd.h>\n\n#include <librex.h>\n#include <bpf/libbpf.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/map_bench\"\n\nint main(void)\n{\n\tstruct bpf_object *obj;\n\tstruct bpf_program *prog;\n\tstruct bpf_link *link = NULL;\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\tprog = bpf_object__find_program_by_name(obj, \"rex_prog1\");\n\tif (!prog) {\n\t\tfprintf(stderr, \"Program not found\\n\");\n\t\treturn 1;\n\t}\n\n\tlink = bpf_program__attach(prog);\n\tif (libbpf_get_error(link)) {\n\t\tfprintf(stderr, \"ERROR: bpf_program__attach failed\\n\");\n\t\tlink = NULL;\n\t\treturn 1;\n\t}\n\n\tbpf_link__pin(link, \"/sys/fs/bpf/link\");\n\tbpf_link__destroy(link);\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/map_bench/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nsample_clippy = custom_target(\n  'map_bench-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsample_build = custom_target(\n  'map_bench-build',\n  output: ['map_bench'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nexecutable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\nexecutable(\n  'event-trigger',\n  'event-trigger.c',\n  build_by_default: true,\n  dependencies: [kernel_dep],\n  pie: true\n)\n\n"
  },
  {
    "path": "samples/map_bench/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/map_bench/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n\nextern crate rex;\n\nuse rex::kprobe::*;\nuse rex::linux::bpf::*;\nuse rex::map::*;\nuse rex::pt_regs::PtRegs;\nuse rex::{Result, rex_kprobe, rex_map, rex_printk};\n\n#[rex_map]\nstatic MAP_HASH: RexHashMap<u32, u64> = RexHashMap::new(5000, 0);\n\n#[rex_map]\nstatic MAP_ARRAY: RexArrayMap<u64> = RexArrayMap::new(5000, 0);\n\n#[rex_kprobe(function = \"kprobe_target_func\")]\nfn rex_prog1(obj: &kprobe, _ctx: &mut PtRegs) -> Result {\n    let zero = 2500u32;\n\n    let random = obj.bpf_get_prandom_u32() as u64;\n    obj.bpf_map_update_elem(&MAP_HASH, &zero, &random, BPF_ANY as u64)?;\n\n    let start = obj.bpf_ktime_get_ns();\n    obj.bpf_map_lookup_elem(&MAP_HASH, &zero);\n    let end = obj.bpf_ktime_get_ns();\n\n    rex_printk!(\"Time elapsed: {}\", end - start)?;\n\n    // let random = obj.bpf_get_prandom_u32() as u64;\n    // obj.bpf_map_update_elem(&MAP_ARRAY, &zero, &random, BPF_ANY as u64)?;\n    //\n    // let start = obj.bpf_ktime_get_ns();\n    // obj.bpf_map_lookup_elem(&MAP_ARRAY, &zero);\n    // let end = obj.bpf_ktime_get_ns();\n    //\n    // rex_printk!(\"Time elapsed: {}\", end - start)?;\n\n    Ok(0)\n}\n"
  },
  {
    "path": "samples/map_test/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/map_test/Cargo.toml",
    "content": "[package]\nname = \"map_test\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/map_test/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/map_test/event-trigger.c",
    "content": "#include <unistd.h>\n#include <linux/unistd.h>\n\nint main(void)\n{\n\treturn syscall(__NR_dup, 1);\n}\n"
  },
  {
    "path": "samples/map_test/loader.c",
    "content": "#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\n#include <linux/perf_event.h>\n#include <linux/unistd.h>\n\n#include <librex.h>\n#include <bpf/libbpf.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/map_test\"\n\nint main(void)\n{\n\tint trace_pipe_fd;\n\tstruct bpf_object *obj;\n\tstruct bpf_program *prog;\n\tstruct bpf_link *link = NULL;\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\tprog = bpf_object__find_program_by_name(obj, \"rex_prog1\");\n\tif (!prog) {\n\t\tfprintf(stderr, \"Program not found\\n\");\n\t\treturn 1;\n\t}\n\n\tlink = bpf_program__attach(prog);\n\tif (libbpf_get_error(link)) {\n\t\tfprintf(stderr, \"ERROR: bpf_program__attach failed\\n\");\n\t\tlink = NULL;\n\t\treturn 1;\n\t}\n\n\ttrace_pipe_fd = openat(AT_FDCWD, \"/sys/kernel/debug/tracing/trace_pipe\",\n\t\t\t       O_RDONLY);\n\n\tfor (;;) {\n\t\tchar c;\n\t\tfflush(stdout);\n\t\tif (read(trace_pipe_fd, &c, 1) == 1)\n\t\t\tputchar(c);\n\t}\n\n\tbpf_link__destroy(link);\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/map_test/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nmap_test_clippy = custom_target(\n  'map_test-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nmap_test_build = custom_target(\n  'map_test-build',\n  output: ['map_test'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nmap_test_loader = executable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\nmap_test_trigger = executable(\n  'event-trigger',\n  'event-trigger.c',\n  build_by_default: true,\n  dependencies: [kernel_dep],\n  pie: true\n)\n\nsanity_test = custom_target(\n  'sanity_test',\n  output: ['runtest.py'],\n  input: join_paths(meson.current_source_dir(), 'tests/runtest.py'),\n  command: [\n    'cp', '@INPUT@', '@OUTPUT@',\n    ]\n )\n\nruntest_deps = [\n  map_test_build,\n  map_test_loader,\n  map_test_trigger,\n  sanity_test\n]\n\nsanity_test_env = environment()\nsanity_test_env.set('SAMPLE_PATH', meson.current_build_dir())\nsanity_test_env.set('Q_SCRIPT',\n  join_paths(meson.project_source_root(), 'scripts/q-script/sanity-test-q')\n)\nsanity_test_env.set('KERNEL_PATH', kbuild_dir)\n\ntest('map_test',\n  python3_bin,\n  args: [sanity_test_scripts],\n  env: sanity_test_env,\n  depends: runtest_deps,\n  is_parallel: false,\n  workdir: meson.current_build_dir()\n)\n"
  },
  {
    "path": "samples/map_test/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/map_test/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n\nextern crate rex;\n\nuse rex::linux::bpf::BPF_ANY;\nuse rex::map::*;\nuse rex::tracepoint::*;\nuse rex::{Result, rex_map, rex_printk, rex_tracepoint};\n\n#[rex_map]\nstatic MAP_HASH: RexHashMap<u32, i64> = RexHashMap::new(1024, 0);\n\n#[rex_map]\nstatic MAP_ARRAY: RexArrayMap<u64> = RexArrayMap::new(256, 0);\n\nfn map_test1(obj: &tracepoint<SyscallsEnterDupCtx>) -> Result {\n    let key: u32 = 0;\n\n    rex_printk!(\"Map Testing 1 Start with key {}\\n\", key)?;\n\n    match obj.bpf_map_lookup_elem(&MAP_HASH, &key) {\n        None => {\n            rex_printk!(\"Not found.\\n\")?;\n        }\n        Some(val) => {\n            rex_printk!(\"Found Val={}.\\n\", *val)?;\n        }\n    }\n\n    let pid = if let Some(task) = obj.bpf_get_current_task() {\n        task.get_pid()\n    } else {\n        -1\n    };\n    rex_printk!(\"Rust program triggered from PID {}\\n\", pid)?;\n\n    obj.bpf_map_update_elem(&MAP_HASH, &key, &(pid as i64), BPF_ANY as u64)?;\n    rex_printk!(\"Map Updated\\n\")?;\n\n    match obj.bpf_map_lookup_elem(&MAP_HASH, &key) {\n        None => {\n            rex_printk!(\"Not found.\\n\")?;\n        }\n        Some(val) => {\n            rex_printk!(\"Found Val={}.\\n\", *val)?;\n        }\n    }\n\n    obj.bpf_map_delete_elem(&MAP_HASH, &key)?;\n    rex_printk!(\"Map delete key\\n\")?;\n\n    match obj.bpf_map_lookup_elem(&MAP_HASH, &key) {\n        None => {\n            rex_printk!(\"Not found.\\n\")?;\n        }\n        Some(val) => {\n            rex_printk!(\"Found Val={}.\\n\", *val)?;\n        }\n    }\n\n    Ok(0)\n}\n\nfn map_test2(obj: &tracepoint<SyscallsEnterDupCtx>) -> Result {\n    rex_printk!(\"Array Map Testing Start\\n\")?;\n    let key = 0;\n\n    let pid = if let Some(task) = obj.bpf_get_current_task() {\n        task.get_pid()\n    } else {\n        -1\n    };\n    rex_printk!(\"Rust program triggered from PID {}\\n\", pid)?;\n\n    // Add a new element\n    obj.bpf_map_update_elem(&MAP_ARRAY, &key, &(pid as u64), BPF_ANY as u64)?;\n    rex_printk!(\"Map Updated\\n\")?;\n\n    match obj.bpf_map_lookup_elem(&MAP_ARRAY, &key) {\n        None => {\n            rex_printk!(\"Not found.\\n\")?;\n        }\n        Some(val) => {\n            rex_printk!(\"Found Val={}.\\n\", *val)?;\n        }\n    }\n    // let ret = obj.bpf_map_push_elem(MAP_ARRAY, pid as u64, BPF_EXIST.into());\n    // rex_printk!(obj, \"Map push ret={}\\n\", ret)?;\n\n    Ok(0)\n}\n\n#[rex_tracepoint]\nfn rex_prog1(\n    obj: &tracepoint<SyscallsEnterDupCtx>,\n    _: &'static SyscallsEnterDupCtx,\n) -> Result {\n    map_test1(obj)\n        .or_else(|e| rex_printk!(\"map_test1 failed with {}.\\n\", e))?;\n    map_test2(obj).or_else(|e| rex_printk!(\"map_test2 failed with {}.\\n\", e))\n}\n"
  },
  {
    "path": "samples/map_test/tests/runtest.py",
    "content": "#!/bin/python\n\nimport re\nimport subprocess\nfrom time import sleep\n\nprocess = 0\n\n\ndef count_bpf_programs():\n    try:\n        # Run bpftool to list all loaded BPF programs\n        result = subprocess.run(\n            \"bpftool prog show\",\n            capture_output=True,\n            shell=True,\n            text=True,\n        )\n\n        # Process the output to count programs\n        if result.stdout:\n            # Each program details start on a new line\n            output = result.stdout.strip().split(\"\\n\")\n            programs = [line for line in output if \"name\" in line]\n            return len(programs)\n        else:\n            return 0\n    except FileNotFoundError:\n        print(\"bpftool is not installed or not found in the PATH.\")\n        return 0\n    except Exception as e:\n        print(f\"An error occurred: {e}\")\n        return 0\n\n\ndef run_loader():\n    global process\n    process = subprocess.Popen(\n        [\"./loader\"],\n        text=True,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n    )\n\n\ndef trigger_prog():\n    try:\n        subprocess.run(\"./event-trigger\", shell=True)\n    except subprocess.CalledProcessError:\n        print(\"CalledProcessError\")\n\n\ndef capture_output() -> bool:\n    try:\n        global process\n        trigger_prog()\n\n        sleep(2)\n        process.kill()\n        std_out, std_err = process.communicate(timeout=7)\n        test_title = re.findall(r\"Map Testing 1 Start with key 0\", std_out, re.M)\n        re_match = re.findall(r\"Rust program triggered from PID (\\d+)\", std_out, re.M)\n        print(std_out)\n        if len(re_match) == 2 and len(test_title) == 1:\n            pid = re_match[0]\n            print(pid)\n            map_match = re.findall(r\"Found Val={}.\".format(pid), std_out, re.M)\n            print(map_match)\n            if len(map_match) == 2:\n                print(\"Success\")\n                return True\n\n        return False\n\n    except subprocess.CalledProcessError:\n        return False\n    except subprocess.TimeoutExpired:\n        process.kill()\n        return False\n\n\ndef main():\n\n    old_prog_num = count_bpf_programs()\n    run_loader()\n    count = 0\n    while old_prog_num == count_bpf_programs():\n        sleep(1)\n        count += 1\n        if count == 5:\n            break\n    grade_file = open(\"auto_grade.txt\", \"w\")\n    if capture_output():\n        grade_file.write(\"success\")\n    else:\n        grade_file.write(\"fail\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "samples/map_test_2/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/map_test_2/Cargo.toml",
    "content": "[package]\nname = \"map_test_2\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/map_test_2/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/map_test_2/event-trigger.c",
    "content": "#include <unistd.h>\n#include <linux/unistd.h>\n\nint main(void)\n{\n\treturn syscall(__NR_dup, 1);\n}\n"
  },
  {
    "path": "samples/map_test_2/loader.c",
    "content": "#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\n#include <linux/perf_event.h>\n#include <linux/unistd.h>\n\n#include <librex.h>\n#include <bpf/libbpf.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/map_test_2\"\n\nint main(void)\n{\n\tint trace_pipe_fd;\n\tstruct bpf_object *obj;\n\tstruct bpf_program *prog;\n\tstruct bpf_link *link = NULL;\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\tprog = bpf_object__find_program_by_name(obj, \"rex_prog1\");\n\tif (!prog) {\n\t\tfprintf(stderr, \"Program not found\\n\");\n\t\treturn 1;\n\t}\n\n\tlink = bpf_program__attach(prog);\n\tif (libbpf_get_error(link)) {\n\t\tfprintf(stderr, \"ERROR: bpf_program__attach failed\\n\");\n\t\tlink = NULL;\n\t\treturn 1;\n\t}\n\n\ttrace_pipe_fd = openat(AT_FDCWD, \"/sys/kernel/debug/tracing/trace_pipe\",\n\t\t\t       O_RDONLY);\n\n\tfor (;;) {\n\t\tchar c;\n\t\tfflush(stdout);\n\t\tif (read(trace_pipe_fd, &c, 1) == 1)\n\t\t\tputchar(c);\n\t}\n\n\tbpf_link__destroy(link);\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/map_test_2/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nmap_test_2_clippy = custom_target(\n  'map_test_2-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nmap_test_2_build = custom_target(\n  'map_test_2-build',\n  output: ['map_test_2'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nmap_test_2_loader = executable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\nmap_test_2_trigger = executable(\n  'event-trigger',\n  'event-trigger.c',\n  build_by_default: true,\n  dependencies: [kernel_dep],\n  pie: true\n)\n\nsanity_test = custom_target(\n  'sanity_test',\n  output: ['runtest.py'],\n  input: join_paths(meson.current_source_dir(), 'tests/runtest.py'),\n  command: [\n    'cp', '@INPUT@', '@OUTPUT@',\n    ]\n )\n\nruntest_deps += [\n  map_test_2_build,\n  map_test_2_loader,\n  map_test_2_trigger,\n  sanity_test\n]\n\nsanity_test_env = environment()\nsanity_test_env.set('SAMPLE_PATH', meson.current_build_dir())\nsanity_test_env.set('Q_SCRIPT',\n  join_paths(meson.project_source_root(), 'scripts/q-script/sanity-test-q')\n)\nsanity_test_env.set('KERNEL_PATH', kbuild_dir)\n\ntest('map_test_2',\n  python3_bin,\n  args: [sanity_test_scripts],\n  env: sanity_test_env,\n  depends: runtest_deps,\n  is_parallel: false,\n  workdir: meson.current_build_dir()\n)\n"
  },
  {
    "path": "samples/map_test_2/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/map_test_2/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n\nextern crate rex;\n\nuse core::mem;\n\nuse rex::map::*;\nuse rex::tracepoint::*;\nuse rex::utils::convert_slice_to_struct_mut;\nuse rex::{Result, rex_map, rex_printk, rex_tracepoint};\n\n#[rex_map]\nstatic MAP_HASH: RexHashMap<u32, i64> = RexHashMap::new(1024, 0);\n\n#[rex_map]\nstatic ARRAY: RexArrayMap<i64> = RexArrayMap::new(256, 0);\n\n#[rex_map]\nstatic STACK: RexStack<i64> = RexStack::new(256, 0);\n\n#[rex_map]\nstatic QUEUE: RexQueue<i64> = RexQueue::new(256, 0);\n\n#[rex_map]\nstatic RINGBUF: RexRingBuf = RexRingBuf::new(4096, 0);\n\nfn map_test_hash(obj: &tracepoint<SyscallsEnterDupCtx>) -> Result {\n    let key: u32 = 0;\n\n    rex_printk!(\"Map Testing Hash Start with key {}\\n\", key)?;\n\n    match MAP_HASH.get_mut(&key) {\n        None => {\n            rex_printk!(\"Not found.\\n\")?;\n        }\n        Some(val) => {\n            rex_printk!(\"Found Val={}.\\n\", *val)?;\n        }\n    }\n\n    let pid = if let Some(task) = obj.bpf_get_current_task() {\n        task.get_pid()\n    } else {\n        -1\n    };\n    rex_printk!(\"Rust program triggered from PID {}\\n\", pid)?;\n\n    MAP_HASH.insert(&key, &(pid as i64))?;\n    rex_printk!(\"Map Updated\\n\")?;\n\n    match MAP_HASH.get_mut(&key) {\n        None => {\n            rex_printk!(\"Not found.\\n\")?;\n        }\n        Some(val) => {\n            rex_printk!(\"Found Val={}.\\n\", *val)?;\n        }\n    }\n\n    MAP_HASH.delete(&key)?;\n    rex_printk!(\"Map delete key\\n\")?;\n\n    match MAP_HASH.get_mut(&key) {\n        None => {\n            rex_printk!(\"Not found.\\n\")?;\n        }\n        Some(val) => {\n            rex_printk!(\"Found Val={}.\\n\", *val)?;\n        }\n    }\n\n    Ok(0)\n}\n\nfn map_test_array(obj: &tracepoint<SyscallsEnterDupCtx>) -> Result {\n    let key: u32 = 0;\n\n    rex_printk!(\"Map Testing Array Start with key {}\\n\", key)?;\n\n    let pid = if let Some(task) = obj.bpf_get_current_task() {\n        task.get_pid()\n    } else {\n        -1\n    };\n    rex_printk!(\"Rust program triggered from PID {}\\n\", pid)?;\n\n    ARRAY.insert(&key, &(pid as i64))?;\n    rex_printk!(\"Map Updated\\n\")?;\n\n    match ARRAY.get_mut(&key) {\n        None => {\n            rex_printk!(\"Not found.\\n\")?;\n        }\n        Some(val) => {\n            rex_printk!(\"Found Val={}.\\n\", *val)?;\n        }\n    }\n\n    Ok(0)\n}\n\nfn map_test_stack(obj: &tracepoint<SyscallsEnterDupCtx>) -> Result {\n    rex_printk!(\"Map Testing Stack Start\\n\")?;\n\n    let pid = if let Some(task) = obj.bpf_get_current_task() {\n        task.get_pid()\n    } else {\n        -1\n    };\n    rex_printk!(\"Rust program triggered from PID {}\\n\", pid)?;\n\n    STACK.push(&(pid as i64))?;\n    rex_printk!(\"Pushed {} onto stack\\n\", pid)?;\n\n    STACK.push(&((pid + 1) as i64))?;\n    rex_printk!(\"Pushed {} onto stack\\n\", pid + 1)?;\n\n    match STACK.peek() {\n        None => rex_printk!(\"Not found.\\n\")?,\n        Some(top) => rex_printk!(\"Top of stack: {}.\\n\", top)?,\n    };\n\n    STACK.pop();\n    rex_printk!(\"Popped top of stack\\n\")?;\n\n    match STACK.peek() {\n        None => rex_printk!(\"Not found.\\n\")?,\n        Some(next_top) => rex_printk!(\"Next top of stack: {}.\\n\", next_top)?,\n    };\n\n    Ok(0)\n}\n\nfn map_test_queue(obj: &tracepoint<SyscallsEnterDupCtx>) -> Result {\n    rex_printk!(\"Map Testing Queue Start\\n\")?;\n\n    let pid = if let Some(task) = obj.bpf_get_current_task() {\n        task.get_pid()\n    } else {\n        -1\n    };\n    rex_printk!(\"Rust program triggered from PID {}\\n\", pid)?;\n\n    QUEUE.push(&(pid as i64))?;\n    rex_printk!(\"Pushed {} into queue\\n\", pid)?;\n\n    QUEUE.push(&((pid + 1) as i64))?;\n    rex_printk!(\"Pushed {} into queue\\n\", pid + 1)?;\n\n    match QUEUE.peek() {\n        None => rex_printk!(\"Not found.\\n\")?,\n        Some(front) => rex_printk!(\"Front of queue: {}.\\n\", front)?,\n    };\n\n    QUEUE.pop();\n    rex_printk!(\"Popped front of queue\\n\")?;\n\n    match QUEUE.peek() {\n        None => rex_printk!(\"Not found.\\n\")?,\n        Some(next_front) => {\n            rex_printk!(\"Next front of queue: {}.\\n\", next_front)?\n        }\n    };\n    Ok(0)\n}\n\nfn map_test_ringbuf(obj: &tracepoint<SyscallsEnterDupCtx>) -> Result {\n    rex_printk!(\"Map Testing Ring Buffer Start\\n\")?;\n    let pid = if let Some(task) = obj.bpf_get_current_task() {\n        task.get_pid()\n    } else {\n        -1\n    };\n    rex_printk!(\"Rust program triggered from PID {}\\n\", pid)?;\n\n    rex_printk!(\n        \"Available bytes in ringbuf: {}\\n\",\n        RINGBUF.available_bytes().unwrap()\n    )?;\n\n    let mut entry = match RINGBUF.reserve(mem::size_of::<i64>()) {\n        None => {\n            rex_printk!(\"Unable to reserve ringbuf.\\n\")?;\n            return Err(0);\n        }\n        Some(entry) => entry,\n    };\n\n    *convert_slice_to_struct_mut::<i64>(&mut entry) = pid as i64;\n\n    entry.submit(0);\n\n    rex_printk!(\n        \"Available bytes in ringbuf: {}\\n\",\n        RINGBUF.available_bytes().unwrap()\n    )?;\n\n    Ok(0)\n}\n\n#[rex_tracepoint]\nfn rex_prog1(\n    obj: &tracepoint<SyscallsEnterDupCtx>,\n    _: &'static SyscallsEnterDupCtx,\n) -> Result {\n    map_test_hash(obj)\n        .or_else(|e| rex_printk!(\"map_test failed with {}.\\n\", e))?;\n    map_test_array(obj)\n        .or_else(|e| rex_printk!(\"map_test failed with {}.\\n\", e))?;\n    map_test_stack(obj)\n        .or_else(|e| rex_printk!(\"map_test failed with {}.\\n\", e))?;\n    map_test_ringbuf(obj)\n        .or_else(|e| rex_printk!(\"map_test2 failed with {}.\\n\", e))?;\n    map_test_queue(obj)\n        .or_else(|e| rex_printk!(\"map_test failed with {}.\\n\", e))\n}\n"
  },
  {
    "path": "samples/map_test_2/tests/runtest.py",
    "content": "#!/bin/python\n\nimport re\nimport subprocess\nfrom time import sleep\n\nprocess = 0\n\n\ndef count_bpf_programs():\n    try:\n        # Run bpftool to list all loaded BPF programs\n        result = subprocess.run(\n            \"bpftool prog show\",\n            capture_output=True,\n            shell=True,\n            text=True,\n        )\n\n        # Process the output to count programs\n        if result.stdout:\n            # Each program details start on a new line\n            output = result.stdout.strip().split(\"\\n\")\n            programs = [line for line in output if \"name\" in line]\n            return len(programs)\n        else:\n            return 0\n    except FileNotFoundError:\n        print(\"bpftool is not installed or not found in the PATH.\")\n        return 0\n    except Exception as e:\n        print(f\"An error occurred: {e}\")\n        return 0\n\n\ndef run_loader():\n    global process\n    process = subprocess.Popen(\n        [\"./loader\"],\n        text=True,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n    )\n\n\ndef trigger_prog():\n    try:\n        subprocess.run(\"./event-trigger\", shell=True)\n    except subprocess.CalledProcessError:\n        print(\"CalledProcessError\")\n\n\ndef capture_output() -> bool:\n    try:\n        global process\n        trigger_prog()\n\n        sleep(2)\n        process.kill()\n        std_out, std_err = process.communicate(timeout=7)\n        test_title = re.findall(r\"Map Testing Hash Start with key 0\", std_out, re.M)\n        re_match = re.findall(r\"Rust program triggered from PID (\\d+)\", std_out, re.M)\n        print(std_out)\n        if len(re_match) == 5 and len(test_title) == 1:\n            pid = re_match[0]\n            print(pid)\n            map_match = re.findall(r\"Found Val={}.\".format(pid), std_out, re.M)\n            stack_match_1 = re.findall(r\"Top of stack: {}.\".format(int(pid) + 1), std_out, re.M)\n            stack_match_2 = re.findall(r\"Next top of stack: {}.\".format(pid), std_out, re.M)\n            queue_match_1 = re.findall(r\"Front of queue: {}.\".format(pid), std_out, re.M)\n            queue_match_2 = re.findall(r\"Next front of queue: {}.\".format(int(pid) + 1), std_out, re.M)\n            ringbuf_match = re.findall(r\"Available bytes in ringbuf\", std_out, re.M)\n            print(map_match)\n            print(stack_match_1)\n            print(stack_match_2)\n            print(queue_match_1)\n            print(queue_match_2)\n            if len(map_match) == 2 and stack_match_1 and stack_match_2 and queue_match_1 and queue_match_2 and len(ringbuf_match) == 2:\n                print(\"Success\")\n                return True\n\n        return False\n\n    except subprocess.CalledProcessError:\n        return False\n    except subprocess.TimeoutExpired:\n        process.kill()\n        return False\n\n\ndef main():\n\n    old_prog_num = count_bpf_programs()\n    run_loader()\n    count = 0\n    while old_prog_num == count_bpf_programs():\n        sleep(1)\n        count += 1\n        if count == 5:\n            break\n    grade_file = open(\"auto_grade.txt\", \"w\")\n    if capture_output():\n        grade_file.write(\"success\")\n    else:\n        grade_file.write(\"fail\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "samples/meson.build",
    "content": "subdir('atomic')\nsubdir('bmc')\nsubdir('electrode')\nsubdir('error_injector')\nsubdir('hello')\nsubdir('map_bench')\nsubdir('map_test')\nsubdir('map_test_2')\nsubdir('recursive')\nsubdir('spinlock_cleanup_benchmark')\nsubdir('spinlock_test')\nsubdir('startup_overhead_benchmark')\nsubdir('syscall_tp')\nsubdir('trace_event')\nsubdir('tracex5')\nsubdir('xdp_test')\nsubdir('syscount')\n"
  },
  {
    "path": "samples/recursive/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/recursive/Cargo.toml",
    "content": "[package]\nname = \"recursive\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/recursive/bench.sh",
    "content": "#!/usr/bin/env bash\n\nif [ \"$#\" -ne 1 ]; then\n\techo \"Usage: $0 <bpf|rex>\"\n\texit 1\nfi\n\necho 8192 > /sys/kernel/debug/tracing/buffer_size_kb\nmkdir output\n\nif [[ \"$1\" == \"rex\" ]]; then\n\tfor i in {0..32}; do\n\t\t./event-trigger 5000 $i\n\t\tcat /sys/kernel/debug/tracing/trace | tail -5000 >\"./output/rust_${i}\"\n\t\techo >/sys/kernel/debug/tracing/trace\n\t\techo $i\n\t\tsleep 0.5\n\tdone\nelif [[ \"$1\" == \"bpf\" ]]; then\n\tfor i in {0..32}; do\n\t\t./event-trigger 6000 $i\n\t\tcat /sys/kernel/debug/tracing/trace | tail -5000  >\"./output/bpf_${i}\"\n\t\techo >/sys/kernel/debug/tracing/trace\n\t\techo $i\n\t\tsleep 0.5\n\tdone\nfi\n\n# unlink\nrm -rf /sys/fs/bpf/*\n"
  },
  {
    "path": "samples/recursive/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/recursive/event-trigger.c",
    "content": "#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\nint main(int argc, char *argv[])\n{\n\tint nr_rounds, arg, fd;\n\n\tif (argc != 3)\n\t\tasm volatile(\"ud2\");\n\n\tnr_rounds = atoi(argv[1]);\n\targ = atoi(argv[2]);\n\tfd = open(\"/proc/kprobe_target\", O_RDONLY);\n\tif (fd < 0) {\n\t\tperror(\"open\");\n\t\treturn 1;\n\t}\n\n\tfor (int i = 0; i < nr_rounds; i++)\n\t\tioctl(fd, 1313, arg);\n\n\tclose(fd);\n}\n"
  },
  {
    "path": "samples/recursive/loader.c",
    "content": "#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\n#include <linux/perf_event.h>\n#include <linux/unistd.h>\n\n#include <librex.h>\n#include <bpf/bpf.h>\n#include <bpf/libbpf.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/recursive\"\n\nint main(void)\n{\n\tstruct bpf_object *obj;\n\tstruct bpf_program *prog;\n\tstruct bpf_link *link = NULL;\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\tprog = bpf_object__find_program_by_name(obj, \"rex_recursive\");\n\tif (!prog) {\n\t\tfprintf(stderr, \"_start not found\\n\");\n\t\treturn 1;\n\t}\n\n\tlink = bpf_program__attach(prog);\n\tif (libbpf_get_error(link)) {\n\t\tfprintf(stderr, \"ERROR: bpf_program__attach failed\\n\");\n\t\tlink = NULL;\n\t\treturn 1;\n\t}\n\n\tbpf_link__pin(link, \"/sys/fs/bpf/recursive_link\");\n\tbpf_link__destroy(link);\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/recursive/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nsample_clippy = custom_target(\n  'recursive-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsample_build = custom_target(\n  'recursive-build',\n  output: ['recursive'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nexecutable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\nexecutable(\n  'event-trigger',\n  'event-trigger.c',\n  build_by_default: true,\n  dependencies: [kernel_dep],\n  pie: true\n)\n\n"
  },
  {
    "path": "samples/recursive/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/recursive/src/main.rs",
    "content": "#![no_std]\n#![no_main]\nextern crate rex;\n\n// use rex::tracepoint::*;\nuse core::hint::black_box;\n\nuse rex::kprobe::*;\nuse rex::map::RexArrayMap;\nuse rex::pt_regs::PtRegs;\nuse rex::{Result, rex_kprobe, rex_map, rex_printk};\n\n#[rex_map]\nstatic data_map: RexArrayMap<u32> = RexArrayMap::new(2, 0);\n\n#[rex_kprobe(function = \"kprobe_target_func\")]\nfn rex_recursive(obj: &kprobe, ctx: &mut PtRegs) -> Result {\n    // let curr_pid: i32 = if let Some(task_struct) = obj.bpf_get_current_task()\n    // {     task_struct.get_pid()\n    // } else {\n    //     return Err(0);\n    // };\n\n    // let stored_pid: u32 = if let Some(val) =\n    // obj.bpf_map_lookup_elem(&data_map, &0) {     *val\n    // } else {\n    //     return Err(0);\n    // };\n\n    let n = ctx.rdi() as u32;\n    // let n: u32 = if let Some(val) = obj.bpf_map_lookup_elem(&data_map, &1) {\n    //     *val\n    // } else {\n    //     return Err(0);\n    // };\n\n    // rex_printk!(\"Received n: {}\", n)?;\n    let start_time: u64 = obj.bpf_ktime_get_ns();\n    calculate_tail_fib(n);\n    let end_time: u64 = obj.bpf_ktime_get_ns();\n    // rex_printk!(\"Result: {}\", result)?;\n\n    rex_printk!(\"Time: {}\", end_time - start_time)?;\n\n    Ok(0)\n}\n\n#[inline(never)]\nfn calculate_tail_fib(n: u32) {\n    if n == 0 {\n        return;\n    }\n\n    black_box(calculate_tail_fib(n - 1))\n}\n"
  },
  {
    "path": "samples/spinlock_cleanup_benchmark/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/spinlock_cleanup_benchmark/.gitignore",
    "content": "target\n"
  },
  {
    "path": "samples/spinlock_cleanup_benchmark/Cargo.toml",
    "content": "[package]\nname = \"spinlock_cleanup_benchmark\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/spinlock_cleanup_benchmark/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/spinlock_cleanup_benchmark/loader.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <sched.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <sys/resource.h>\n#include <sys/wait.h>\n#include <linux/types.h>\n#include <linux/if_link.h>\n\n#include <bpf/bpf.h>\n#include <bpf/libbpf.h>\n\n#include <librex.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/spinlock_cleanup_benchmark\"\n\n#define __unused __attribute__((__unused__))\n\nint main(int __unused argc, char **argv)\n{\n\tstruct bpf_program *prog;\n\tstruct bpf_object *obj;\n\n\tint interface_idx = atoi(argv[1]);\n\tunsigned int xdp_flags = 0;\n\txdp_flags |= XDP_FLAGS_DRV_MODE;\n\t/* xdp_flags |= XDP_FLAGS_SKB_MODE; */\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\tprog = bpf_object__find_program_by_name(obj, \"rex_prog1\");\n\tif (!prog) {\n\t\tprintf(\"finding a prog in obj file failed\\n\");\n\t\treturn 1;\n\t}\n\tint xdp_main_prog_fd = bpf_program__fd(prog);\n\n\tif (bpf_xdp_attach(interface_idx, xdp_main_prog_fd, xdp_flags, NULL) <\n\t    0) {\n\t\tfprintf(stderr, \"ERROR: xdp failed\");\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/spinlock_cleanup_benchmark/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nsample_clippy = custom_target(\n  'spinlock_cleanup_benchmark-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsample_build = custom_target(\n  'spinlock_cleanup_benchmark-build',\n  output: ['spinlock_cleanup_benchmark'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nexecutable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\n"
  },
  {
    "path": "samples/spinlock_cleanup_benchmark/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/spinlock_cleanup_benchmark/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n\nextern crate rex;\n\nuse rex::linux::bpf::bpf_spin_lock;\nuse rex::map::RexArrayMap;\nuse rex::spinlock::rex_spinlock_guard;\nuse rex::xdp::*;\nuse rex::{Result, rex_map, rex_printk, rex_xdp};\n\n#[repr(C)]\n#[derive(Clone, Copy)]\nstruct MapEntry {\n    data: u64,\n    lock: bpf_spin_lock,\n}\n\n#[rex_map]\nstatic MAP_ARRAY: RexArrayMap<MapEntry> = RexArrayMap::new(256, 0);\n\n#[rex_xdp]\nfn rex_prog1(obj: &xdp, _: &mut xdp_md) -> Result {\n    if let Some(entry) = obj.bpf_map_lookup_elem(&MAP_ARRAY, &0) {\n        let start = obj.bpf_ktime_get_ns();\n        {\n            let _guard = rex_spinlock_guard::new(&mut entry.lock);\n        }\n        let end = obj.bpf_ktime_get_ns();\n        rex_printk!(\"Spinlock allocation and cleanup: {} ns\", end - start)?;\n        Ok(XDP_PASS as i32)\n    } else {\n        rex_printk!(\"Unable to look up map\")?;\n        Err(XDP_PASS as i32)\n    }\n}\n"
  },
  {
    "path": "samples/spinlock_test/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/spinlock_test/.gitignore",
    "content": "target\n"
  },
  {
    "path": "samples/spinlock_test/Cargo.toml",
    "content": "[package]\nname = \"spinlock_test\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/spinlock_test/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/spinlock_test/event-trigger.c",
    "content": "#include <unistd.h>\n#include <linux/unistd.h>\n\nint main(void)\n{\n\treturn syscall(__NR_dup, 1);\n}\n"
  },
  {
    "path": "samples/spinlock_test/loader.c",
    "content": "#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <linux/perf_event.h>\n#include <linux/unistd.h>\n\n#include <librex.h>\n#include <bpf/libbpf.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/spinlock_test\"\n\nint main(void)\n{\n\tint trace_pipe_fd;\n\tstruct bpf_object *obj;\n\tstruct bpf_program *prog;\n\tstruct bpf_link *link = NULL;\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\tprog = bpf_object__find_program_by_name(obj, \"rex_prog1\");\n\tif (!prog) {\n\t\tfprintf(stderr, \"_start not found\\n\");\n\t\treturn 1;\n\t}\n\n\tlink = bpf_program__attach(prog);\n\tif (libbpf_get_error(link)) {\n\t\tfprintf(stderr, \"ERROR: bpf_program__attach failed\\n\");\n\t\tlink = NULL;\n\t\treturn 1;\n\t}\n\n\ttrace_pipe_fd = openat(AT_FDCWD, \"/sys/kernel/debug/tracing/trace_pipe\",\n\t\t\t       O_RDONLY);\n\n\tfor (;;) {\n\t\tchar c;\n\t\tif (read(trace_pipe_fd, &c, 1) == 1)\n\t\t\tputchar(c);\n\t}\n\n\tbpf_link__destroy(link);\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/spinlock_test/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nsample_clippy = custom_target(\n  'spinlock_test-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsample_build = custom_target(\n  'spinlock_test-build',\n  output: ['spinlock_test'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nexecutable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\nexecutable(\n  'event-trigger',\n  'event-trigger.c',\n  build_by_default: true,\n  dependencies: [kernel_dep],\n  pie: true\n)\n\n"
  },
  {
    "path": "samples/spinlock_test/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/spinlock_test/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n\nextern crate rex;\n\nuse rex::linux::bpf::bpf_spin_lock;\nuse rex::map::RexArrayMap;\nuse rex::spinlock::rex_spinlock_guard;\nuse rex::tracepoint::*;\nuse rex::{Result, rex_map, rex_tracepoint};\n\n#[repr(C)]\n#[derive(Clone, Copy)]\nstruct MapEntry {\n    data: u64,\n    lock: bpf_spin_lock,\n}\n\n#[rex_map]\nstatic MAP_ARRAY: RexArrayMap<MapEntry> = RexArrayMap::new(256, 0);\n\nfn test1(obj: &tracepoint<SyscallsEnterDupCtx>) {\n    if let Some(entry) = obj.bpf_map_lookup_elem(&MAP_ARRAY, &0) {\n        // entry.lock locked in rex_spinlock_guard::new\n        let _guard = rex_spinlock_guard::new(&mut entry.lock);\n        entry.data = 1;\n        // entry.lock is automatically released when _guard goes out of scope\n    }\n}\n\nfn test2(obj: &tracepoint<SyscallsEnterDupCtx>) {\n    if let Some(entry) = obj.bpf_map_lookup_elem(&MAP_ARRAY, &0) {\n        // entry.lock locked in rex_spinlock_guard::new\n        let _guard = rex_spinlock_guard::new(&mut entry.lock);\n        entry.data = 1;\n        panic!(\"test\\n\");\n        // entry.lock is automatically released by cleanup mechanism\n    }\n}\n\n#[rex_tracepoint]\nfn rex_prog1(\n    obj: &tracepoint<SyscallsEnterDupCtx>,\n    _: &'static SyscallsEnterDupCtx,\n) -> Result {\n    test1(obj);\n    test2(obj);\n    Ok(0)\n}\n"
  },
  {
    "path": "samples/startup_overhead_benchmark/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/startup_overhead_benchmark/.gitignore",
    "content": "target\n"
  },
  {
    "path": "samples/startup_overhead_benchmark/Cargo.toml",
    "content": "[package]\nname = \"startup_overhead_benchmark\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/startup_overhead_benchmark/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/startup_overhead_benchmark/event-trigger.c",
    "content": "#include <fcntl.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\nint main(int argc, char *argv[])\n{\n\tint nr_rounds, arg, fd;\n\n\tif (argc != 3)\n\t\tasm volatile(\"ud2\");\n\n\tnr_rounds = atoi(argv[1]);\n\targ = atoi(argv[2]);\n\tfd = open(\"/proc/kprobe_target\", O_RDONLY);\n\tif (fd < 0) {\n\t\tperror(\"open\");\n\t\treturn 1;\n\t}\n\n\tfor (int i = 0; i < nr_rounds; i++)\n\t\tioctl(fd, 1313, arg);\n\n\tclose(fd);\n}\n"
  },
  {
    "path": "samples/startup_overhead_benchmark/loader.c",
    "content": "#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n\n#include <linux/perf_event.h>\n#include <linux/unistd.h>\n\n#include <librex.h>\n#include <bpf/libbpf.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/startup_overhead_benchmark\"\n\nint main(void)\n{\n\tstruct bpf_object *obj;\n\tstruct bpf_program *prog;\n\tstruct bpf_link *link = NULL;\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\tprog = bpf_object__find_program_by_name(obj, \"rex_prog1\");\n\tif (!prog) {\n\t\tfprintf(stderr, \"_start not found\\n\");\n\t\treturn 1;\n\t}\n\n\tlink = bpf_program__attach(prog);\n\tif (libbpf_get_error(link)) {\n\t\tfprintf(stderr, \"ERROR: bpf_program__attach failed\\n\");\n\t\tlink = NULL;\n\t\treturn 1;\n\t}\n\n\tbpf_link__pin(link, \"/sys/fs/bpf/kprobe_link\");\n\tbpf_link__destroy(link);\n\treturn 0;\n}\n"
  },
  {
    "path": "samples/startup_overhead_benchmark/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nsample_clippy = custom_target(\n  'startup_overhead_benchmark-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsample_build = custom_target(\n  'startup_overhead_benchmark-build',\n  output: ['startup_overhead_benchmark'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nexecutable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\nexecutable(\n  'event-trigger',\n  'event-trigger.c',\n  build_by_default: true,\n  dependencies: [kernel_dep],\n  pie: true\n)\n\n"
  },
  {
    "path": "samples/startup_overhead_benchmark/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/startup_overhead_benchmark/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n\nextern crate rex;\n\nuse rex::kprobe::*;\nuse rex::pt_regs::PtRegs;\nuse rex::{Result, rex_kprobe};\n\n#[rex_kprobe(function = \"kprobe_target_func\")]\nfn rex_prog1(_obj: &kprobe, _ctx: &mut PtRegs) -> Result {\n    Ok(0)\n}\n"
  },
  {
    "path": "samples/syscount/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n    \"-Zthreads=8\",\n    \"-Cforce-frame-pointers=y\",\n    \"-Csymbol-mangling-version=v0\",\n    \"-Ccodegen-units=1\",\n    \"-Crelocation-model=pie\",\n    \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/syscount/Cargo.toml",
    "content": "[package]\nname = \"syscount\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n"
  },
  {
    "path": "samples/syscount/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/syscount/loader.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include <string.h>\n#include <bpf/libbpf.h>\n#include <bpf/bpf.h>\n#include <librex.h>\n#include <time.h>\n#include <errno.h>\n\n#define EXE \"./target/x86_64-unknown-none/release/syscount\"\n\n#define __unused __attribute__((__unused__))\n\nstatic const char *syscall_names[] = {\n\t\"read\",\t\t\"write\",\t\"open\",\t\t  \"close\",\n\t\"stat\",\t\t\"fstat\",\t\"lstat\",\t  \"poll\",\n\t\"lseek\",\t\"mmap\",\t\t\"mprotect\",\t  \"munmap\",\n\t\"brk\",\t\t\"rt_sigaction\", \"rt_sigprocmask\", \"rt_sigreturn\",\n\t\"ioctl\",\t\"pread64\",\t\"pwrite64\",\t  \"readv\",\n\t\"writev\",\t\"access\",\t\"pipe\",\t\t  \"select\",\n\t\"sched_yield\",\t\"mremap\",\t\"msync\",\t  \"mincore\",\n\t\"madvise\",\t\"shmget\",\t\"shmat\",\t  \"shmctl\",\n\t\"dup\",\t\t\"dup2\",\t\t\"pause\",\t  \"nanosleep\",\n\t\"getitimer\",\t\"alarm\",\t\"setitimer\",\t  \"getpid\",\n\t\"sendfile\",\t\"socket\",\t\"connect\",\t  \"accept\",\n\t\"sendto\",\t\"recvfrom\",\t\"sendmsg\",\t  \"recvmsg\",\n\t\"shutdown\",\t\"bind\",\t\t\"listen\",\t  \"getsockname\",\n\t\"getpeername\",\t\"socketpair\",\t\"setsockopt\",\t  \"getsockopt\",\n\t\"clone\",\t\"fork\",\t\t\"vfork\",\t  \"execve\",\n\t\"exit\",\t\t\"wait4\",\t\"kill\",\t\t  \"uname\",\n\t\"semget\",\t\"semop\",\t\"semctl\",\t  \"shmdt\",\n\t\"msgget\",\t\"msgsnd\",\t\"msgrcv\",\t  \"msgctl\",\n\t\"fcntl\",\t\"flock\",\t\"fsync\",\t  \"fdatasync\",\n\t\"truncate\",\t\"ftruncate\",\t\"getdents\",\t  \"getcwd\",\n\t\"chdir\",\t\"fchdir\",\t\"rename\",\t  \"mkdir\",\n\t\"rmdir\",\t\"creat\",\t\"link\",\t\t  \"unlink\",\n\t\"symlink\",\t\"readlink\",\t\"chmod\",\t  \"fchmod\",\n\t\"chown\",\t\"fchown\",\t\"lchown\",\t  \"umask\",\n\t\"gettimeofday\", \"getrlimit\",\t\"getrusage\",\t  \"sysinfo\"\n};\n\n#define MAX_SYSCALL_ID (sizeof(syscall_names) / sizeof(syscall_names[0]))\n\nstatic volatile bool exiting = false;\n\nstatic void sig_handler(int __unused sig)\n{\n\texiting = true;\n}\n\nenum stats_type_t { COUNT_ONLY, SHOW_ERRORS, SHOW_LATENCY, SHOW_BOTH };\n\nstatic void print_header(bool timestamp, enum stats_type_t type)\n{\n\tif (timestamp) {\n\t\tprintf(\"%-8s \", \"TIME(s)\");\n\t}\n\n\tswitch (type) {\n\tcase COUNT_ONLY:\n\t\tprintf(\"%-20s %-10s\\n\", \"SYSCALL\", \"COUNT\");\n\t\tbreak;\n\tcase SHOW_ERRORS:\n\t\tprintf(\"%-20s %-10s %-10s\\n\", \"SYSCALL\", \"COUNT\", \"ERRORS\");\n\t\tbreak;\n\tcase SHOW_LATENCY:\n\t\tprintf(\"%-20s %-10s %-15s\\n\", \"SYSCALL\", \"COUNT\", \"TIME(us)\");\n\t\tbreak;\n\tcase SHOW_BOTH:\n\t\tprintf(\"%-20s %-10s %-10s %-15s\\n\", \"SYSCALL\", \"COUNT\",\n\t\t       \"ERRORS\", \"TIME(us)\");\n\t\tbreak;\n\t}\n\n\tif (timestamp) {\n\t\tprintf(\"%-8s \", \"--------\");\n\t}\n\n\tswitch (type) {\n\tcase COUNT_ONLY:\n\t\tprintf(\"%-20s %-10s\\n\", \"--------------------\", \"----------\");\n\t\tbreak;\n\tcase SHOW_ERRORS:\n\t\tprintf(\"%-20s %-10s %-10s\\n\", \"--------------------\",\n\t\t       \"----------\", \"----------\");\n\t\tbreak;\n\tcase SHOW_LATENCY:\n\t\tprintf(\"%-20s %-10s %-15s\\n\", \"--------------------\",\n\t\t       \"----------\", \"---------------\");\n\t\tbreak;\n\tcase SHOW_BOTH:\n\t\tprintf(\"%-20s %-10s %-10s %-15s\\n\", \"--------------------\",\n\t\t       \"----------\", \"----------\", \"---------------\");\n\t\tbreak;\n\t}\n}\n\nstruct options {\n\tint interval;\n\tbool timestamp;\n\tbool clear_screen;\n\tbool sort_by_count;\n\tint top_n;\n\tenum stats_type_t type;\n\tint pid;\n\tchar *filter_syscalls;\n};\n\nstatic void print_usage(const char *prog_name)\n{\n\tprintf(\"Usage: %s [options]\\n\\n\", prog_name);\n\tprintf(\"Options:\\n\");\n\tprintf(\"  -i <seconds>   Set the output interval (default: 1 second)\\n\");\n\tprintf(\"  -t             Include timestamp in output\\n\");\n\tprintf(\"  -c             Clear the screen between outputs\\n\");\n\tprintf(\"  -s             Sort by syscall name instead of count\\n\");\n\tprintf(\"  -n <count>     Display only the top N syscalls\\n\");\n\tprintf(\"  -e             Show errors count\\n\");\n\tprintf(\"  -l             Show latency (average time per syscall in microseconds)\\n\");\n\tprintf(\"  -p <pid>       Filter by process ID\\n\");\n\tprintf(\"  -x <syscalls>  Trace only comma-separated syscalls\\n\");\n\tprintf(\"  -h             Display this help message\\n\");\n}\n\nstatic struct options parse_options(int argc, char *argv[])\n{\n\tstatic struct options opts = { .interval = 1,\n\t\t\t\t       .timestamp = false,\n\t\t\t\t       .clear_screen = false,\n\t\t\t\t       .sort_by_count = true,\n\t\t\t\t       .top_n = -1,\n\t\t\t\t       .type = COUNT_ONLY,\n\t\t\t\t       .pid = -1,\n\t\t\t\t       .filter_syscalls = NULL };\n\n\tint c;\n\twhile ((c = getopt(argc, argv, \"i:tcn:selp:x:h\")) != -1) {\n\t\tswitch (c) {\n\t\tcase 'i':\n\t\t\topts.interval = atoi(optarg);\n\t\t\tif (opts.interval <= 0)\n\t\t\t\topts.interval = 1;\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\topts.timestamp = true;\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\topts.clear_screen = true;\n\t\t\tbreak;\n\t\tcase 'n':\n\t\t\topts.top_n = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\topts.sort_by_count = false;\n\t\t\tbreak;\n\t\tcase 'e':\n\t\t\tif (opts.type == SHOW_LATENCY)\n\t\t\t\topts.type = SHOW_BOTH;\n\t\t\telse\n\t\t\t\topts.type = SHOW_ERRORS;\n\t\t\tbreak;\n\t\tcase 'l':\n\t\t\tif (opts.type == SHOW_ERRORS)\n\t\t\t\topts.type = SHOW_BOTH;\n\t\t\telse\n\t\t\t\topts.type = SHOW_LATENCY;\n\t\t\tbreak;\n\t\tcase 'p':\n\t\t\topts.pid = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'x':\n\t\t\topts.filter_syscalls = optarg;\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\tprint_usage(argv[0]);\n\t\t\texit(0);\n\t\tdefault:\n\t\t\tprint_usage(argv[0]);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\n\treturn opts;\n}\n\nint main(int argc, char *argv[])\n{\n\tstruct bpf_object *obj;\n\tstruct bpf_link **links = NULL;\n\tint link_count = 0;\n\tint syscall_counts_map_fd = -1;\n\tint syscall_errors_map_fd = -1;\n\tint syscall_latency_map_fd = -1;\n\ttime_t start_time;\n\tint err = 0;\n\n\tstruct options opts = parse_options(argc, argv);\n\n\tsignal(SIGINT, sig_handler);\n\tsignal(SIGTERM, sig_handler);\n\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Failed to load BPF program\\n\");\n\t\treturn 1;\n\t}\n\n\tint prog_count = 0;\n\tstruct bpf_program *prog;\n\n\tbpf_object__for_each_program(prog, obj) {\n\t\tprog_count++;\n\t}\n\n\tlinks = calloc(prog_count, sizeof(struct bpf_link *));\n\tif (!links) {\n\t\tfprintf(stderr, \"Failed to allocate memory for links\\n\");\n\t\treturn 1;\n\t}\n\n\tbpf_object__for_each_program(prog, obj) {\n\t\tlinks[link_count] = bpf_program__attach(prog);\n\t\tif (libbpf_get_error(links[link_count])) {\n\t\t\tfprintf(stderr, \"Failed to attach program: %s\\n\",\n\t\t\t\tbpf_program__name(prog));\n\t\t\terr = -1;\n\t\t} else {\n\t\t\tprintf(\"Attached program: %s\\n\",\n\t\t\t       bpf_program__name(prog));\n\t\t\tlink_count++;\n\t\t}\n\t}\n\n\tif (err != 0) {\n\t\tfprintf(stderr, \"Failed to attach some programs\\n\");\n\t\tgoto cleanup;\n\t}\n\tsyscall_counts_map_fd =\n\t\tbpf_object__find_map_fd_by_name(obj, \"SYSCALL_COUNTS\");\n\tif (syscall_counts_map_fd < 0) {\n\t\tfprintf(stderr, \"Failed to find syscall counts map\\n\");\n\t\terr = -1;\n\t\tgoto cleanup;\n\t}\n\n\tif (opts.type == SHOW_ERRORS || opts.type == SHOW_BOTH) {\n\t\tsyscall_errors_map_fd =\n\t\t\tbpf_object__find_map_fd_by_name(obj, \"SYSCALL_ERRORS\");\n\t\tif (syscall_errors_map_fd < 0) {\n\t\t\tfprintf(stderr, \"Failed to find syscall errors map\\n\");\n\t\t\topts.type = opts.type == SHOW_BOTH ? SHOW_LATENCY :\n\t\t\t\t\t\t\t     COUNT_ONLY;\n\t\t}\n\t}\n\n\tif (opts.type == SHOW_LATENCY || opts.type == SHOW_BOTH) {\n\t\tsyscall_latency_map_fd =\n\t\t\tbpf_object__find_map_fd_by_name(obj, \"SYSCALL_LATENCY\");\n\t\tif (syscall_latency_map_fd < 0) {\n\t\t\tfprintf(stderr, \"Failed to find syscall latency map\\n\");\n\t\t\topts.type = opts.type == SHOW_BOTH ? SHOW_ERRORS :\n\t\t\t\t\t\t\t     COUNT_ONLY;\n\t\t}\n\t}\n\n\tprintf(\"Tracing syscalls... Hit Ctrl-C to end.\\n\");\n\tstart_time = time(NULL);\n\n\twhile (!exiting) {\n\t\tsleep(opts.interval);\n\n\t\tif (opts.clear_screen) {\n\t\t\tprintf(\"\\033[2J\\033[1;1H\");\n\t\t}\n\n\t\tprint_header(opts.timestamp, opts.type);\n\n\t\t__u32 key = 0, next_key;\n\t\t__u64 count_value, error_value = 0, latency_value = 0;\n\n\t\tstruct {\n\t\t\t__u32 id;\n\t\t\t__u64 count;\n\t\t\t__u64 errors;\n\t\t\t__u64 latency;\n\t\t} stats[512];\n\t\tint stat_count = 0;\n\n\t\twhile (bpf_map_get_next_key(syscall_counts_map_fd, &key,\n\t\t\t\t\t    &next_key) == 0) {\n\t\t\tif (bpf_map_lookup_elem(syscall_counts_map_fd,\n\t\t\t\t\t\t&next_key, &count_value) == 0) {\n\t\t\t\tstats[stat_count].id = next_key;\n\t\t\t\tstats[stat_count].count = count_value;\n\n\t\t\t\tif (syscall_errors_map_fd >= 0 &&\n\t\t\t\t    bpf_map_lookup_elem(syscall_errors_map_fd,\n\t\t\t\t\t\t\t&next_key,\n\t\t\t\t\t\t\t&error_value) == 0) {\n\t\t\t\t\tstats[stat_count].errors = error_value;\n\t\t\t\t} else {\n\t\t\t\t\tstats[stat_count].errors = 0;\n\t\t\t\t}\n\n\t\t\t\tif (syscall_latency_map_fd >= 0 &&\n\t\t\t\t    bpf_map_lookup_elem(syscall_latency_map_fd,\n\t\t\t\t\t\t\t&next_key,\n\t\t\t\t\t\t\t&latency_value) == 0) {\n\t\t\t\t\tstats[stat_count].latency =\n\t\t\t\t\t\tlatency_value;\n\t\t\t\t} else {\n\t\t\t\t\tstats[stat_count].latency = 0;\n\t\t\t\t}\n\n\t\t\t\tstat_count++;\n\t\t\t}\n\t\t\tkey = next_key;\n\t\t}\n\n\t\tif (opts.sort_by_count) {\n\t\t\tfor (int i = 0; i < stat_count - 1; i++) {\n\t\t\t\tfor (int j = 0; j < stat_count - i - 1; j++) {\n\t\t\t\t\tif (stats[j].count <\n\t\t\t\t\t    stats[j + 1].count) {\n\t\t\t\t\t\t__u32 temp_id = stats[j].id;\n\t\t\t\t\t\t__u64 temp_count =\n\t\t\t\t\t\t\tstats[j].count;\n\t\t\t\t\t\t__u64 temp_errors =\n\t\t\t\t\t\t\tstats[j].errors;\n\t\t\t\t\t\t__u64 temp_latency =\n\t\t\t\t\t\t\tstats[j].latency;\n\n\t\t\t\t\t\tstats[j].id = stats[j + 1].id;\n\t\t\t\t\t\tstats[j].count =\n\t\t\t\t\t\t\tstats[j + 1].count;\n\t\t\t\t\t\tstats[j].errors =\n\t\t\t\t\t\t\tstats[j + 1].errors;\n\t\t\t\t\t\tstats[j].latency =\n\t\t\t\t\t\t\tstats[j + 1].latency;\n\n\t\t\t\t\t\tstats[j + 1].id = temp_id;\n\t\t\t\t\t\tstats[j + 1].count = temp_count;\n\t\t\t\t\t\tstats[j + 1].errors =\n\t\t\t\t\t\t\ttemp_errors;\n\t\t\t\t\t\tstats[j + 1].latency =\n\t\t\t\t\t\t\ttemp_latency;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (int i = 0; i < stat_count - 1; i++) {\n\t\t\t\tfor (int j = 0; j < stat_count - i - 1; j++) {\n\t\t\t\t\tif (stats[j].id > stats[j + 1].id) {\n\t\t\t\t\t\t__u32 temp_id = stats[j].id;\n\t\t\t\t\t\t__u64 temp_count =\n\t\t\t\t\t\t\tstats[j].count;\n\t\t\t\t\t\t__u64 temp_errors =\n\t\t\t\t\t\t\tstats[j].errors;\n\t\t\t\t\t\t__u64 temp_latency =\n\t\t\t\t\t\t\tstats[j].latency;\n\n\t\t\t\t\t\tstats[j].id = stats[j + 1].id;\n\t\t\t\t\t\tstats[j].count =\n\t\t\t\t\t\t\tstats[j + 1].count;\n\t\t\t\t\t\tstats[j].errors =\n\t\t\t\t\t\t\tstats[j + 1].errors;\n\t\t\t\t\t\tstats[j].latency =\n\t\t\t\t\t\t\tstats[j + 1].latency;\n\n\t\t\t\t\t\tstats[j + 1].id = temp_id;\n\t\t\t\t\t\tstats[j + 1].count = temp_count;\n\t\t\t\t\t\tstats[j + 1].errors =\n\t\t\t\t\t\t\ttemp_errors;\n\t\t\t\t\t\tstats[j + 1].latency =\n\t\t\t\t\t\t\ttemp_latency;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tint display_count = stat_count;\n\t\tif (opts.top_n > 0 && opts.top_n < stat_count) {\n\t\t\tdisplay_count = opts.top_n;\n\t\t}\n\n\t\tfor (int i = 0; i < display_count; i++) {\n\t\t\tconst char *name;\n\t\t\tif (stats[i].id < MAX_SYSCALL_ID) {\n\t\t\t\tname = syscall_names[stats[i].id];\n\t\t\t} else {\n\t\t\t\tname = \"unknown\";\n\t\t\t}\n\n\t\t\tif (opts.timestamp) {\n\t\t\t\tprintf(\"%-8ld \", time(NULL) - start_time);\n\t\t\t}\n\n\t\t\tswitch (opts.type) {\n\t\t\tcase COUNT_ONLY:\n\t\t\t\tprintf(\"%-20s %-10llu\\n\", name, stats[i].count);\n\t\t\t\tbreak;\n\n\t\t\tcase SHOW_ERRORS:\n\t\t\t\tprintf(\"%-20s %-10llu %-10llu\\n\", name,\n\t\t\t\t       stats[i].count, stats[i].errors);\n\t\t\t\tbreak;\n\n\t\t\tcase SHOW_LATENCY: {\n\t\t\t\tdouble avg_us = 0;\n\t\t\t\tif (stats[i].count > 0) {\n\t\t\t\t\tavg_us = (double)stats[i].latency /\n\t\t\t\t\t\t stats[i].count /\n\t\t\t\t\t\t 1000.0; // ns to us\n\t\t\t\t}\n\t\t\t\tprintf(\"%-20s %-10llu %-15.2f\\n\", name,\n\t\t\t\t       stats[i].count, avg_us);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase SHOW_BOTH: {\n\t\t\t\tdouble avg_us = 0;\n\t\t\t\tif (stats[i].count > 0) {\n\t\t\t\t\tavg_us = (double)stats[i].latency /\n\t\t\t\t\t\t stats[i].count /\n\t\t\t\t\t\t 1000.0; // ns to us\n\t\t\t\t}\n\t\t\t\tprintf(\"%-20s %-10llu %-10llu %-15.2f\\n\", name,\n\t\t\t\t       stats[i].count, stats[i].errors, avg_us);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t__u64 total_count = 0, total_errors = 0, total_latency = 0;\n\t\tfor (int i = 0; i < stat_count; i++) {\n\t\t\ttotal_count += stats[i].count;\n\t\t\ttotal_errors += stats[i].errors;\n\t\t\ttotal_latency += stats[i].latency;\n\t\t}\n\n\t\tif (opts.timestamp) {\n\t\t\tprintf(\"%-8ld \", time(NULL) - start_time);\n\t\t}\n\n\t\tswitch (opts.type) {\n\t\tcase COUNT_ONLY:\n\t\t\tprintf(\"%-20s %-10llu\\n\", \"TOTAL\", total_count);\n\t\t\tbreak;\n\n\t\tcase SHOW_ERRORS:\n\t\t\tprintf(\"%-20s %-10llu %-10llu\\n\", \"TOTAL\", total_count,\n\t\t\t       total_errors);\n\t\t\tbreak;\n\n\t\tcase SHOW_LATENCY: {\n\t\t\tdouble avg_us = 0;\n\t\t\tif (total_count > 0) {\n\t\t\t\tavg_us = (double)total_latency / total_count /\n\t\t\t\t\t 1000.0; // ns to us\n\t\t\t}\n\t\t\tprintf(\"%-20s %-10llu %-15.2f\\n\", \"TOTAL\", total_count,\n\t\t\t       avg_us);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase SHOW_BOTH: {\n\t\t\tdouble avg_us = 0;\n\t\t\tif (total_count > 0) {\n\t\t\t\tavg_us = (double)total_latency / total_count /\n\t\t\t\t\t 1000.0; // ns to us\n\t\t\t}\n\t\t\tprintf(\"%-20s %-10llu %-10llu %-15.2f\\n\", \"TOTAL\",\n\t\t\t       total_count, total_errors, avg_us);\n\t\t\tbreak;\n\t\t}\n\t\t}\n\n\t\tprintf(\"\\n\");\n\t}\n\ncleanup:\n\tprintf(\"\\nDetaching programs\\n\");\n\tfor (int i = 0; i < link_count; i++) {\n\t\tbpf_link__destroy(links[i]);\n\t}\n\tfree(links);\n\treturn err;\n}\n"
  },
  {
    "path": "samples/syscount/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nsyscount_clippy = custom_target(\n  'syscount-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsyscount_build = custom_target(\n  'syscount-build',\n  output: ['syscount'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: syscount_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsyscount_loader = executable(\n  'loader',\n  'loader.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n"
  },
  {
    "path": "samples/syscount/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/syscount/src/main.rs",
    "content": "#![no_std]\n#![no_main]\nextern crate rex;\n\nuse rex::linux::bpf::BPF_ANY;\nuse rex::map::RexHashMap;\nuse rex::tracepoint::*;\nuse rex::{Result, rex_map, rex_tracepoint};\n\n#[rex_map]\nstatic SYSCALL_COUNTS: RexHashMap<u32, u64> = RexHashMap::new(512, 0);\n\n#[rex_map]\nstatic SYSCALL_ERRORS: RexHashMap<u32, u64> = RexHashMap::new(512, 0);\n\n#[rex_map]\nstatic SYSCALL_START: RexHashMap<u64, u64> = RexHashMap::new(1024, 0);\n\n#[rex_map]\nstatic SYSCALL_LATENCY: RexHashMap<u32, u64> = RexHashMap::new(512, 0);\n\n// Tracepoint handler for raw_syscalls:sys_enter\n#[rex_tracepoint]\nfn trace_syscall_enter(\n    obj: &tracepoint<RawSyscallsEnterCtx>,\n    ctx: &'static RawSyscallsEnterCtx,\n) -> Result {\n    let syscall_id = ctx.id as u32;\n\n    match obj.bpf_map_lookup_elem(&SYSCALL_COUNTS, &syscall_id) {\n        Some(count) => {\n            *count += 1;\n        }\n        None => {\n            obj.bpf_map_update_elem(\n                &SYSCALL_COUNTS,\n                &syscall_id,\n                &1,\n                BPF_ANY as u64,\n            )?;\n        }\n    }\n    if let Some(task) = obj.bpf_get_current_task() {\n        let pid_tgid =\n            ((task.get_tgid() as u64) << 32) | (task.get_pid() as u64);\n        let key = (syscall_id as u64) | (pid_tgid << 32);\n        let start_time = obj.bpf_ktime_get_ns();\n\n        obj.bpf_map_update_elem(\n            &SYSCALL_START,\n            &key,\n            &start_time,\n            BPF_ANY as u64,\n        )?;\n    }\n\n    Ok(0)\n}\n\n// Tracepoint handler for raw_syscalls:sys_exit\n#[rex_tracepoint]\nfn trace_syscall_exit(\n    obj: &tracepoint<RawSyscallsExitCtx>,\n    ctx: &'static RawSyscallsExitCtx,\n) -> Result {\n    let syscall_id = ctx.id as u32;\n    let ret = ctx.ret;\n\n    if ret < 0 {\n        match obj.bpf_map_lookup_elem(&SYSCALL_ERRORS, &syscall_id) {\n            Some(count) => {\n                *count += 1;\n            }\n            None => {\n                obj.bpf_map_update_elem(\n                    &SYSCALL_ERRORS,\n                    &syscall_id,\n                    &1,\n                    BPF_ANY as u64,\n                )?;\n            }\n        }\n    }\n\n    if let Some(task) = obj.bpf_get_current_task() {\n        let pid_tgid =\n            ((task.get_tgid() as u64) << 32) | (task.get_pid() as u64);\n        let key = (syscall_id as u64) | (pid_tgid << 32);\n\n        if let Some(start_time) = obj.bpf_map_lookup_elem(&SYSCALL_START, &key)\n        {\n            let now = obj.bpf_ktime_get_ns();\n            let delta = now - *start_time;\n\n            match obj.bpf_map_lookup_elem(&SYSCALL_LATENCY, &syscall_id) {\n                Some(total) => {\n                    *total += delta;\n                }\n                None => {\n                    obj.bpf_map_update_elem(\n                        &SYSCALL_LATENCY,\n                        &syscall_id,\n                        &delta,\n                        BPF_ANY as u64,\n                    )?;\n                }\n            }\n\n            obj.bpf_map_delete_elem(&SYSCALL_START, &key)?;\n        }\n    }\n\n    Ok(0)\n}\n"
  },
  {
    "path": "samples/xdp_test/.cargo/config.toml",
    "content": "[build]\ntarget = \"x86_64-unknown-none\"\n\n[target.x86_64-unknown-none]\nlinker = \"ld.mold\"\nrustflags = [\n  \"-Zthreads=8\",\n  \"-Cforce-frame-pointers=y\",\n  \"-Csymbol-mangling-version=v0\",\n  \"-Ccodegen-units=1\",\n  \"-Crelocation-model=pie\",\n  \"-Crelro-level=full\",\n]\n\n[unstable]\nbuild-std = [\"core\"]\n"
  },
  {
    "path": "samples/xdp_test/Cargo.toml",
    "content": "[package]\nname = \"xdp_test\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\n\n[dependencies.rex]\npath = \"../../rex\"\n\n[lints.clippy]\ndisallowed_methods = \"forbid\"\ndisallowed_types = \"forbid\"\n\n[lints.rust]\nincomplete_features = \"forbid\"\ninternal_features = \"forbid\"\nunsafe_code = \"forbid\"\nunstable_features = \"forbid\"\n\n[profile.dev]\npanic = \"abort\"\ndebug = false\n\n[profile.release]\npanic = \"abort\"\ndebug = false\nlto = true\n\n"
  },
  {
    "path": "samples/xdp_test/README.md",
    "content": "<div style=\"text-align: justify;\">\n\n# Onboarding Task: Rust-based extensions\n\n**Note: You need to be on the x86-64 architecture in order to work on this\nMP. We assume the x86-64 architecture and ABI in this writeup.**\n\n**Note2: If you are using aarch64 architecture, you will need to find\nanother x86-64 computer or run this project in emulation**\n\n**Please make sure you read through this document at least once before\nstarting.**\n\n# Table of Contents\n\n- [Introduction](#introduction)\n- [Problem Description](#problem-description)\n  - [eBPF XDP Program](#ebpf-xdp-program)\n- [Implementation Overview](#implementation-overview)\n  - [Understand the rex repo structure](#understand-the-rex-repo-structure)\n    - [Try out the rex xdp sample.](#try-out-the-rex-xdp-sample)\n  - [Make the rex version program](#make-the-rex-version-program)\n- [Other Requirements](#other-requirements)\n- [Resources](#resources)\n\n# Introduction\n\nThe emergence of verified eBPF bytecode is ushering in a new era of safe\nkernel extensions.  In this paper, we argue that eBPF’s verifier—the source\nof its safety guarantees—has become a liability. In addition to the\nwell-known bugs and vulnerabilities stemming from the complexity and ad hoc\nnature of the in-kernel verifier, we highlight a concerning trend in which\nescape hatches to unsafe kernel functions (in the form of helper functions)\nare being introduced to bypass verifier-imposed limitations on\nexpressiveness, unfortunately also bypassing its safety guarantees. We\npropose safe kernel extension frameworks using a balance of not just static\nbut also lightweight runtime techniques. We describe a design centered\naround kernel extensions in safe Rust that will eliminate the need of the\nin-kernel verifier, improve expressiveness, allow for reduced escape\nhatches, and ultimately improve the safety of kernel extensions.\n\nThe basic ideas are documented in [a workshop\npaper](../../docs/rust-kernel-ext.pdf) (no need to read through).\n\n# Problem Description\n\nYour task is to implement an rex program in Rust, equivalent to an eBPF\nversion. This is conceptually straightforward. However, the real challenge\nlies in mastering rex operations and integrating them with your knowledge\nof Linux kernel programming, Rust programming, and other essential aspects\nlike ELF (Executable and Linkable Format). This task will test your\ntechnical skills and ability to quickly adapt to new programming\nenvironments.\n\nTo implement a packet filtering mechanism using both eBPF and an rex\nprogram, your objective is to drop incoming network traffic based on\npredefined rules for port numbers and protocol types (TCP or UDP). The\nsteps you need to follow are:\n\n1. Write an eBPF program that employs the XDP hook to inspect and\n   potentially drop packets at an early stage in the networking stack.\n2. Create a user-space application that interacts with the eBPF program,\n   particularly focusing on updating the rules for packet filtering (such\n   as which ports to block).\n3. Develop an rex program that similarly inspects traffic and creates a\n   user-space application for updating the rules for packet filtering.\n\n![xdp_image](../../docs/image/xdp-attach-point.png)\n\n## eBPF XDP Program\n\nThe eBPF program will be attached to the XDP hook in the Linux kernel. XDP\nprovides high-performance packet processing at the earliest point where a\npacket is received by the network driver.\n\nThe eBPF XDP program will:\n\n1. Inspect each incoming packet's header to determine the port number and\n   protocol (TCP/UDP).\n2. Check against a set of rules defined in a BPF map (a key-value store\n   used by eBPF programs for storing runtime data).\n3. Decide whether to drop the packet or allow it to pass based on these\n   rules.\n\n# Implementation Overview\n\n## Understand the rex repo structure\n\nThe repository contains the following directories:\n\n- `librex`: This is the equivalent of `libbpf` for rex programs. You should\n  not modify any files in this directory.\n- `rex`: This is the runtime crate for rex programs and contains the\n  program type and helper function definitions.\n  - You will need to add helper functions to `src/xdp/xdp_impl.rs` but\n    should avoid changing any other files.\n- `xdp_test`: This is the directory of the program you need to\n  implement.\n  - Specifically, you should place the rex program code in `src/main.rs`\n    and the loader code in `entry.c`.\n\n\n  ## Utilize Nix\nFor this task, we encourage to utilize the support of Nix. Using Nix, a\npackage manager, could allow you to bypass the dependency requirements.\nYou can find the installation steps [here](../../README.org#nix-flake) All\nsubsequent steps should be carried out within this shell.\n\n## Make the rex version program\n\n```bash\n# assume you are in the rex-kernel\ncd xdp_test\n# compile the xdp program\nmake\n# bind xdp program to interface lo\n./entry 1\n```\n\n1. We have provided you with the `samples/xdp_test` directory for\n   the rex version of the XDP program. The function `ip_header` in the\n   `rex/src/xdp/xdp_impl.rs` file is used to parse the IP header from a\n   packet. It is used: `let ip_header = obj.ip_header(ctx);` in\n   `samples/xdp_test/src/main.rs`.\n2. For loader implementation:\n    - One hint is that `rex_obj_load` and `rex_obj_get_bpf` should be used\n      for loading and manipulating rex programs.\n      ```c\n      // load rex obj\n      obj = rex_obj_get_bpf(rex_obj_load(EXE));\n      ```\n    - You need to add additional parameter processing for adding rules,\n      besides the existing binding interface part. Implement the new action\n      `./entry add_rule <port> <protocol>` to add rules to the eBPF map.\n      Adding rules for removal is optional.\n3. You can refer to the `samples/map_test` folder to see how to use the map\n   in Rust.\n\n## Test your implementation\n\n1. To test your implementation, you can use netcat(nc), a utility tool that\n   uses TCP/UDP connections to read/write into the network.\n2. On server: nc -l -p port_number (Start a listener at port_number)\n3. On client: nc 127.0.0.1 port_number (Starts a client)\n4. Note: The above netcat commands are for a TCP connection, for UDP\n   connection, \"-u\" command needs to be added on both server and client.\n5. The logs of bpf_printk, can be found at\n   \"/sys/kernel/debug/tracing/trace_pipe\"\n6. You can update the map using bpftool: bpftool map update id 1 key hex 35\n   00 00 00 value hex 01 00 (Update map with id 1 with hex a value b)\n\n# Other Requirements\n\n- Do not change any other files except the files mentioned above.\n- Your Rust code should not have any `unsafe` block in the rex program, but\n  can have `unsafe` blocks in the `rex` crate.\n- You should not use any other extern crates (i.e. Rust packages) other\n  than the provided `rex`.\n- You cannot use the Rust `std` library because it is not available in\n  standalong mode, but the `core` library remains largely available.\n- This research is currently not available to the public. So please do not\n  put the rex code on GPT.\n\n# Resources\n\nWe recommend you to get your hands dirty directly and check these resources\non demand. In fact, we didn’t know Rust well when we started this project –\nyou can always learn a language by writing the code.\n\n- eBPF: [ebpf.io](https://ebpf.io/) and [The Illustrated Children’s Guide\n  to\n  eBPF](https://ebpf.io/books/buzzing-across-space-illustrated-childrens-guide-to-ebpf.pdf)\n  and [xdp-tutorial](https://github.com/xdp-project/xdp-tutorial) both are\n  good places to start. You can also find the official kernel documentation\n  [here](https://elixir.bootlin.com/linux/v5.15.127/source/Documentation/bpf)\n  along with the source code. In particular, try answering:\n  - What is eBPF?\n  - What is XDP?\n  - What are some example use cases of eBPF?\n  - How are eBPF programs loaded to the kernel and bind XDP program to\n    interfaces?\n  - How are the execution of eBPF programs triggered?\n  - What are eBPF helpers?\n- Rust: If you are not familiar with the Rust program language, we have\n  some resources for you:\n  - [The Rust book](https://doc.rust-lang.org/book/) (Probably the most\n    comprehensive guide on Rust programming)\n  - [Library API reference](https://doc.rust-lang.org/std/index.html) (for\n    searching API specifications)\n  - [The Rust playground](https://play.rust-lang.org) (for trying out\n    programs)\n</div>\n"
  },
  {
    "path": "samples/xdp_test/clippy.toml",
    "content": "disallowed-methods = [\n\t\"core::mem::forget\",\n]\n\ndisallowed-types = [\n\t\"core::mem::ManuallyDrop\",\n]\n"
  },
  {
    "path": "samples/xdp_test/entry.c",
    "content": "#include <assert.h>\n#include <bpf/bpf.h>\n#include <bpf/libbpf.h>\n#include <linux/bpf.h>\n#include <linux/if_link.h>\n#include <linux/limits.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/resource.h>\n#include <time.h>\n#include <unistd.h>\n\n#include <librex.h>\n\n#define BPF_SYSFS_ROOT \"/sys/fs/bpf\"\n\n#define EXE \"./target/x86_64-unknown-none/release/xdp_test\"\n\nstatic int nr_cpus = 0;\n\nstruct bpf_progs_desc {\n\tchar name[256];\n\tenum bpf_prog_type type;\n\tunsigned char pin;\n\tint map_prog_idx;\n\tstruct bpf_program *prog;\n};\n\n;\n\nint main(int argc, char *argv[])\n{\n\tstruct rlimit r = { RLIM_INFINITY, RLIM_INFINITY };\n\tint xdp_main_prog_fd;\n\tstruct bpf_program *rx_prog, *tx_prog;\n\tstruct bpf_object *obj;\n\tchar filename[PATH_MAX];\n\tint err;\n\t__u32 xdp_flags = 0;\n\tint *interfaces_idx;\n\tint ret = 0;\n\n\tint interface_count = 0;\n\tint sig, quit = 0;\n\n\tinterface_count = argc - optind;\n\tif (interface_count <= 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Missing at least one required interface index\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tinterfaces_idx = calloc(sizeof(int), interface_count);\n\tif (interfaces_idx == NULL) {\n\t\tfprintf(stderr, \"Error: failed to allocate memory\\n\");\n\t\treturn 1;\n\t}\n\n\tfor (int i = 0; i < interface_count && optind < argc; optind++, i++) {\n\t\tinterfaces_idx[i] = atoi(argv[optind]);\n\t}\n\tnr_cpus = libbpf_num_possible_cpus();\n\n\tsigset_t signal_mask;\n\tsigemptyset(&signal_mask);\n\tsigaddset(&signal_mask, SIGINT);\n\tsigaddset(&signal_mask, SIGTERM);\n\tsigaddset(&signal_mask, SIGUSR1);\n\n\tif (setrlimit(RLIMIT_MEMLOCK, &r)) {\n\t\tperror(\"setrlimit failed\");\n\t\treturn 1;\n\t}\n\n\t// load rex obj\n\tobj = rex_obj_get_bpf(rex_obj_load(EXE));\n\tif (!obj) {\n\t\tfprintf(stderr, \"Object could not be opened\\n\");\n\t\treturn 1;\n\t}\n\n\trx_prog = bpf_object__find_program_by_name(obj, \"xdp_rx_filter\");\n\tif (!rx_prog) {\n\t\tfprintf(stderr, \"start not found\\n\");\n\t\treturn 1;\n\t}\n\n\txdp_main_prog_fd = bpf_program__fd(rx_prog);\n\tif (xdp_main_prog_fd < 0) {\n\t\tfprintf(stderr, \"Error: bpf_program__fd failed\\n\");\n\t\treturn 1;\n\t}\n\n\t// Some nics do not support XDP DRV mode\n\t// xdp_flags |= XDP_FLAGS_DRV_MODE;\n\txdp_flags |= XDP_FLAGS_SKB_MODE;\n\tfor (int i = 0; i < interface_count; i++) {\n\t\tif (bpf_xdp_attach(interfaces_idx[i], xdp_main_prog_fd,\n\t\t\t\t   xdp_flags, NULL) < 0) {\n\t\t\tfprintf(stderr,\n\t\t\t\t\"Error: bpf_set_link_xdp_fd failed for interface %d\\n\",\n\t\t\t\tinterfaces_idx[i]);\n\t\t\treturn 1;\n\t\t} else {\n\t\t\tprintf(\"Main BPF program attached to XDP on interface %d\\n\",\n\t\t\t       interfaces_idx[i]);\n\t\t}\n\t}\n\n\t// binding sched_cls program\n\tchar prog_name[256] = \"xdp_tx_filter\";\n\ttx_prog = bpf_object__find_program_by_name(obj, prog_name);\n\tif (!tx_prog) {\n\t\tfprintf(stderr, \"tx_prog not found\\n\");\n\t\texit(1);\n\t}\n\tprintf(\"tx_prog: %s\\n\", bpf_program__name(tx_prog));\n\n\tint len = snprintf(filename, PATH_MAX, \"%s/%s\", BPF_SYSFS_ROOT,\n\t\t\t   prog_name);\n\tif (len < 0) {\n\t\tfprintf(stderr, \"Error: Program name '%s' is invalid\\n\",\n\t\t\t\"xdp_tx_filter\");\n\t\treturn -1;\n\t} else if (len >= PATH_MAX) {\n\t\tfprintf(stderr, \"Error: Program name '%s' is too long\\n\",\n\t\t\tprog_name);\n\t\treturn -1;\n\t}\n\n\tret = bpf_program__pin(tx_prog, filename);\n\tif (ret != 0) {\n\t\tfprintf(stderr,\n\t\t\t\"Error: Failed to pin program '%s' to path %s with error code %d\\n\",\n\t\t\tprog_name, filename, ret);\n\t\treturn ret;\n\t}\n\n\terr = sigprocmask(SIG_BLOCK, &signal_mask, NULL);\n\tif (err != 0) {\n\t\tfprintf(stderr, \"Error: Failed to set signal mask\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\twhile (!quit) {\n\t\terr = sigwait(&signal_mask, &sig);\n\t\tif (err != 0) {\n\t\t\tfprintf(stderr, \"Error: Failed to wait for signal\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tswitch (sig) {\n\t\tcase SIGINT:\n\t\tcase SIGTERM:\n\t\tcase SIGUSR1:\n\t\t\tquit = 1;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Unknown signal\\n\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// unattach program\n\tfor (int i = 0; i < interface_count; i++)\n\t\tbpf_xdp_detach(interfaces_idx[i], xdp_flags, NULL);\n\n\treturn ret;\n}\n"
  },
  {
    "path": "samples/xdp_test/meson.build",
    "content": "build_dir = run_command(\n  realpath,\n  '--relative-to',\n  meson.current_source_dir(),\n  meson.current_build_dir(),\n  capture: true,\n  check: true\n).stdout().strip()\n\nenv = environment()\nenv.prepend('PATH', rust_bin)\nenv.set('LINUX_OBJ', kbuild_dir)\nenv.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux'))\nenv.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target'))\n\nsample_clippy = custom_target(\n  'xdp_test-clippy',\n  output: ['target'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'clippy', '-qr'\n  ],\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nsample_build = custom_target(\n  'xdp_test-build',\n  output: ['xdp_test'],\n  command: [\n    cargo_wrapper, rust_bin, '-Z',\n    'unstable-options',\n    '-C', meson.current_source_dir(),\n    'rustc', '-qr', '--',\n    '-Cenable_rex'\n  ],\n  depends: sample_clippy,\n  env: env,\n  console: false,\n  build_by_default: true\n)\n\nxdp_test_entry = executable(\n  'entry',\n  'entry.c',\n  build_by_default: true,\n  dependencies: [librex_dep, libbpf_dep, kernel_dep],\n  pie: true\n)\n\nsanity_test = custom_target(\n  'sanity_test',\n  output: ['runtest.py'],\n  input: join_paths(meson.current_source_dir(), 'tests/runtest.py'),\n  command: [\n    'cp', '@INPUT@', '@OUTPUT@',\n    ]\n )\n\nruntest_deps += [sample_build, xdp_test_entry, sanity_test]\n\nsanity_test_env = environment()\nsanity_test_env.set('SAMPLE_PATH', meson.current_build_dir())\nsanity_test_env.set('Q_SCRIPT',\n  join_paths(meson.project_source_root(), 'scripts/q-script/sanity-test-q')\n)\nsanity_test_env.set('KERNEL_PATH', kbuild_dir)\n\ntest('xdp_test_test', \n  python3_bin, \n  args: [sanity_test_scripts],\n  env: sanity_test_env,\n  depends: runtest_deps,\n  is_parallel: false,\n  workdir: meson.current_build_dir()\n)\n"
  },
  {
    "path": "samples/xdp_test/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "samples/xdp_test/src/main.rs",
    "content": "#![no_std]\n#![no_main]\n#![allow(non_camel_case_types)]\n\nextern crate rex;\n\nuse core::net::Ipv4Addr;\n\nuse rex::sched_cls::*;\nuse rex::utils::*;\nuse rex::xdp::*;\nuse rex::{rex_printk, rex_tc, rex_xdp};\n\n#[rex_xdp]\nfn xdp_rx_filter(obj: &xdp, ctx: &mut xdp_md) -> Result {\n    let mut ip_header = obj.ip_header(ctx);\n\n    rex_printk!(\"IP saddr {}\\n\", Ipv4Addr::from_bits(*ip_header.saddr()))?;\n    rex_printk!(\"IP daddr {}\\n\", Ipv4Addr::from_bits(*ip_header.daddr()))?;\n\n    match u8::from_be(ip_header.protocol) as u32 {\n        IPPROTO_TCP => {\n            rex_printk!(\"TCP packet!\")?;\n        }\n        IPPROTO_UDP => {\n            rex_printk!(\"UDP packet!\")?;\n        }\n        _ => {}\n    };\n\n    Ok(XDP_PASS as i32)\n}\n\n#[rex_tc]\nfn xdp_tx_filter(obj: &sched_cls, skb: &mut __sk_buff) -> Result {\n    let mut ip_header = obj.ip_header(skb);\n\n    rex_printk!(\"IP saddr {}\\n\", Ipv4Addr::from_bits(*ip_header.saddr()))?;\n    rex_printk!(\"IP daddr {}\\n\", Ipv4Addr::from_bits(*ip_header.daddr()))?;\n    if u8::from_be(ip_header.protocol) as u32 == IPPROTO_UDP {\n        return rex_printk!(\"UDP packet!\");\n    }\n\n    Ok(TC_ACT_OK as i32)\n}\n"
  },
  {
    "path": "samples/xdp_test/tests/runtest.py",
    "content": "#!/usr/bin/env python3\n\nimport socket\nimport subprocess\nimport sys\nimport threading\nimport time\nfrom pathlib import Path\n\n\ndef count_bpf_programs():\n    \"\"\"Count currently loaded BPF programs\"\"\"\n    try:\n        result = subprocess.run(\n            \"bpftool prog show\",\n            capture_output=True,\n            shell=True,\n            text=True,\n        )\n\n        if result.stdout:\n            output = result.stdout.strip().split(\"\\n\")\n            programs = [line for line in output if \"name\" in line]\n            return len(programs)\n        else:\n            return 0\n    except FileNotFoundError:\n        print(\"bpftool is not installed or not found in the PATH.\")\n        return 0\n    except Exception as e:\n        print(f\"An error occurred: {e}\")\n        return 0\n\n\ndef generate_traffic():\n    \"\"\"Generate some network traffic on loopback to trigger XDP program\"\"\"\n    try:\n        # Create a UDP socket and send data to localhost\n        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n        sock.sendto(b\"test packet\", (\"127.0.0.1\", 12345))\n        sock.close()\n\n        # TCP attempt\n        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        sock.settimeout(1)\n        try:\n            sock.connect((\"127.0.0.1\", 12346))\n        except (socket.error, ConnectionRefusedError):\n            pass  # Connection will likely fail, but that's okay\n        sock.close()\n\n        time.sleep(0.1)  # Small delay to ensure packets are processed\n\n    except Exception as e:\n        print(f\"Error generating traffic: {e}\")\n        raise e\n\n\ndef get_trace_log():\n    \"\"\"Monitor trace logs for XDP activity\"\"\"\n    xdp_activity = []\n    keywords = (\"IP saddr\", \"IP daddr\", \"TCP packet\", \"UDP packet\")\n\n    try:\n        with open(\"/sys/kernel/debug/tracing/trace\", \"r\") as f:\n            for line in f:\n                if any(k in line for k in keywords):\n                    s = line.rstrip(\"\\n\")\n                    xdp_activity.append(s)\n                    print(f\"XDP trace: {s}\")\n    except Exception as e:\n        print(f\"Error reading trace logs: {e}\")\n\n    return xdp_activity\n\n\ndef test_xdp_program():\n    \"\"\"Main test function for XDP program\"\"\"\n    print(\"Starting XDP program sanity test in QEMU environment...\")\n\n    # Check if we're in the right directory\n    if not Path(\"./entry\").exists():\n        print(\"Error: entry executable not found. Checking current directory...\")\n        print(f\"Current directory: {Path.cwd()}\")\n        print(f\"Directory contents: {list(Path('.').iterdir())}\")\n        return False\n\n    # Count programs before\n    old_prog_count = count_bpf_programs()\n    print(f\"BPF programs before: {old_prog_count}\")\n\n    # Start XDP program in background\n    print(\"Starting XDP program on loopback interface...\")\n    xdp_process = None\n    try:\n        xdp_process = subprocess.Popen(\n            [\"./entry\", \"1\"],\n            text=True,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n        )\n        print(f\"XDP process started with PID: {xdp_process.pid}\")\n\n        # Wait for program to load\n        time.sleep(3)\n\n        # Check if new programs were loaded\n        new_prog_count = count_bpf_programs()\n        print(f\"BPF programs after: {new_prog_count}\")\n\n        if new_prog_count <= old_prog_count:\n            print(\"Warning: No new BPF programs detected\")\n\n        # Generate traffic to trigger XDP\n        print(\"Generating test traffic...\")\n        for i in range(10):\n            generate_traffic()\n            time.sleep(0.3)\n            if i % 3 == 0:\n                print(f\"Generated {i+1} traffic bursts...\")\n\n        # Wait a bit more for logs to appear\n        time.sleep(2)\n\n        # Start get trace logs\n        print(\"Starting trace log retrieving...\")\n        xdp_activity = get_trace_log()\n\n        # Check results\n        program_loaded = new_prog_count > old_prog_count\n        has_activity = len(xdp_activity) > 0\n\n        print(f\"Program loaded: {program_loaded}\")\n        print(f\"XDP activity detected: {has_activity}\")\n        print(f\"Total XDP log entries: {len(xdp_activity)}\")\n\n        if has_activity:\n            print(\"SUCCESS: XDP program is processing packets\")\n            return True\n        else:\n            print(\"FAILURE: XDP program did not load or show activity\")\n            return False\n\n    except Exception as e:\n        print(f\"Error during test: {e}\")\n        return False\n\n    finally:\n        # Clean up\n        print(\"Cleaning up...\")\n        if xdp_process:\n            try:\n                # Send SIGTERM first\n                xdp_process.terminate()\n                xdp_process.wait(timeout=3)\n                print(\"XDP process terminated gracefully\")\n            except subprocess.TimeoutExpired:\n                # Force kill if it doesn't respond\n                xdp_process.kill()\n                print(\"XDP process force killed\")\n            except Exception as e:\n                print(f\"Error during cleanup: {e}\")\n\n\ndef main():\n    \"\"\"Main function\"\"\"\n    success = test_xdp_program()\n\n    # Write result to grade file\n    with open(\"auto_grade.txt\", \"w\") as f:\n        f.write(\"success\" if success else \"fail\")\n\n    print(f\"\\nXDP program sanity test {'PASSED' if success else 'FAILED'}\")\n    return 0 if success else 1\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n"
  },
  {
    "path": "scripts/cargo-wrapper.pl",
    "content": "#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\n\nmy ($build_dir, @cmd) = @ARGV;\nmy $cargo_bin = \"$build_dir/cargo\";\n\nexec($cargo_bin, @cmd);\n"
  },
  {
    "path": "scripts/q-script/.config",
    "content": "#\n# Automatically generated file; DO NOT EDIT.\n# Linux/x86 6.19.0 Kernel Configuration\n#\nCONFIG_CC_VERSION_TEXT=\"clang version 21.1.8\"\nCONFIG_GCC_VERSION=0\nCONFIG_CC_IS_CLANG=y\nCONFIG_CLANG_VERSION=210108\nCONFIG_AS_IS_LLVM=y\nCONFIG_AS_VERSION=210108\nCONFIG_LD_VERSION=0\nCONFIG_LD_IS_LLD=y\nCONFIG_LLD_VERSION=210108\nCONFIG_RUSTC_VERSION=109301\nCONFIG_RUST_IS_AVAILABLE=y\nCONFIG_RUSTC_LLVM_VERSION=210108\nCONFIG_CC_CAN_LINK=y\nCONFIG_CC_HAS_ASM_GOTO_OUTPUT=y\nCONFIG_CC_HAS_ASM_GOTO_TIED_OUTPUT=y\nCONFIG_TOOLS_SUPPORT_RELR=y\nCONFIG_CC_HAS_ASM_INLINE=y\nCONFIG_CC_HAS_ASSUME=y\nCONFIG_CC_HAS_NO_PROFILE_FN_ATTR=y\nCONFIG_CC_HAS_COUNTED_BY=y\nCONFIG_CC_HAS_MULTIDIMENSIONAL_NONSTRING=y\nCONFIG_LD_CAN_USE_KEEP_IN_OVERLAY=y\nCONFIG_RUSTC_HAS_SLICE_AS_FLATTENED=y\nCONFIG_RUSTC_HAS_COERCE_POINTEE=y\nCONFIG_RUSTC_HAS_SPAN_FILE=y\nCONFIG_RUSTC_HAS_UNNECESSARY_TRANSMUTES=y\nCONFIG_RUSTC_HAS_FILE_WITH_NUL=y\nCONFIG_RUSTC_HAS_FILE_AS_C_STR=y\nCONFIG_PAHOLE_VERSION=130\nCONFIG_IRQ_WORK=y\nCONFIG_BUILDTIME_TABLE_SORT=y\nCONFIG_THREAD_INFO_IN_TASK=y\n\n#\n# General setup\n#\nCONFIG_INIT_ENV_ARG_LIMIT=32\n# CONFIG_COMPILE_TEST is not set\n# CONFIG_WERROR is not set\n# CONFIG_UAPI_HEADER_TEST is not set\nCONFIG_LOCALVERSION=\"-rex\"\n# CONFIG_LOCALVERSION_AUTO is not set\nCONFIG_BUILD_SALT=\"\"\nCONFIG_HAVE_KERNEL_GZIP=y\nCONFIG_HAVE_KERNEL_BZIP2=y\nCONFIG_HAVE_KERNEL_LZMA=y\nCONFIG_HAVE_KERNEL_XZ=y\nCONFIG_HAVE_KERNEL_LZO=y\nCONFIG_HAVE_KERNEL_LZ4=y\nCONFIG_HAVE_KERNEL_ZSTD=y\n# CONFIG_KERNEL_GZIP is not set\n# CONFIG_KERNEL_BZIP2 is not set\n# CONFIG_KERNEL_LZMA is not set\n# CONFIG_KERNEL_XZ is not set\n# CONFIG_KERNEL_LZO is not set\n# CONFIG_KERNEL_LZ4 is not set\nCONFIG_KERNEL_ZSTD=y\nCONFIG_DEFAULT_INIT=\"\"\nCONFIG_DEFAULT_HOSTNAME=\"(none)\"\nCONFIG_SYSVIPC=y\nCONFIG_SYSVIPC_SYSCTL=y\nCONFIG_POSIX_MQUEUE=y\nCONFIG_POSIX_MQUEUE_SYSCTL=y\n# CONFIG_WATCH_QUEUE is not set\nCONFIG_CROSS_MEMORY_ATTACH=y\nCONFIG_AUDIT=y\nCONFIG_HAVE_ARCH_AUDITSYSCALL=y\nCONFIG_AUDITSYSCALL=y\n\n#\n# IRQ subsystem\n#\nCONFIG_GENERIC_IRQ_PROBE=y\nCONFIG_GENERIC_IRQ_SHOW=y\nCONFIG_GENERIC_IRQ_EFFECTIVE_AFF_MASK=y\nCONFIG_GENERIC_PENDING_IRQ=y\nCONFIG_GENERIC_IRQ_MIGRATION=y\nCONFIG_HARDIRQS_SW_RESEND=y\nCONFIG_IRQ_DOMAIN=y\nCONFIG_IRQ_DOMAIN_HIERARCHY=y\nCONFIG_GENERIC_MSI_IRQ=y\nCONFIG_GENERIC_IRQ_MATRIX_ALLOCATOR=y\nCONFIG_GENERIC_IRQ_RESERVATION_MODE=y\nCONFIG_IRQ_FORCED_THREADING=y\nCONFIG_SPARSE_IRQ=y\n# CONFIG_GENERIC_IRQ_DEBUGFS is not set\n# end of IRQ subsystem\n\nCONFIG_CLOCKSOURCE_WATCHDOG=y\nCONFIG_ARCH_CLOCKSOURCE_INIT=y\nCONFIG_GENERIC_TIME_VSYSCALL=y\nCONFIG_GENERIC_CLOCKEVENTS=y\nCONFIG_GENERIC_CLOCKEVENTS_BROADCAST=y\nCONFIG_GENERIC_CLOCKEVENTS_BROADCAST_IDLE=y\nCONFIG_GENERIC_CLOCKEVENTS_MIN_ADJUST=y\nCONFIG_GENERIC_CMOS_UPDATE=y\nCONFIG_HAVE_POSIX_CPU_TIMERS_TASK_WORK=y\nCONFIG_POSIX_CPU_TIMERS_TASK_WORK=y\nCONFIG_CONTEXT_TRACKING=y\nCONFIG_CONTEXT_TRACKING_IDLE=y\n\n#\n# Timers subsystem\n#\nCONFIG_TICK_ONESHOT=y\nCONFIG_NO_HZ_COMMON=y\n# CONFIG_HZ_PERIODIC is not set\nCONFIG_NO_HZ_IDLE=y\n# CONFIG_NO_HZ_FULL is not set\nCONFIG_NO_HZ=y\nCONFIG_HIGH_RES_TIMERS=y\nCONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US=125\n# CONFIG_POSIX_AUX_CLOCKS is not set\n# end of Timers subsystem\n\nCONFIG_BPF=y\nCONFIG_HAVE_EBPF_JIT=y\nCONFIG_ARCH_WANT_DEFAULT_BPF_JIT=y\n\n#\n# BPF subsystem\n#\nCONFIG_BPF_SYSCALL=y\nCONFIG_BPF_JIT=y\nCONFIG_BPF_JIT_ALWAYS_ON=y\nCONFIG_BPF_JIT_DEFAULT_ON=y\nCONFIG_BPF_UNPRIV_DEFAULT_OFF=y\n# CONFIG_BPF_PRELOAD is not set\nCONFIG_BPF_LSM=y\n# end of BPF subsystem\n\nCONFIG_PREEMPT_NONE_BUILD=y\nCONFIG_ARCH_HAS_PREEMPT_LAZY=y\nCONFIG_PREEMPT_NONE=y\n# CONFIG_PREEMPT_VOLUNTARY is not set\n# CONFIG_PREEMPT is not set\n# CONFIG_PREEMPT_LAZY is not set\n# CONFIG_PREEMPT_RT is not set\n# CONFIG_PREEMPT_DYNAMIC is not set\n# CONFIG_SCHED_CORE is not set\nCONFIG_SCHED_CLASS_EXT=y\n\n#\n# CPU/Task time and stats accounting\n#\nCONFIG_TICK_CPU_ACCOUNTING=y\n# CONFIG_VIRT_CPU_ACCOUNTING_GEN is not set\n# CONFIG_IRQ_TIME_ACCOUNTING is not set\nCONFIG_BSD_PROCESS_ACCT=y\n# CONFIG_BSD_PROCESS_ACCT_V3 is not set\nCONFIG_TASKSTATS=y\nCONFIG_TASK_DELAY_ACCT=y\nCONFIG_TASK_XACCT=y\nCONFIG_TASK_IO_ACCOUNTING=y\n# CONFIG_PSI is not set\n# end of CPU/Task time and stats accounting\n\nCONFIG_CPU_ISOLATION=y\n\n#\n# RCU Subsystem\n#\nCONFIG_TREE_RCU=y\n# CONFIG_RCU_EXPERT is not set\nCONFIG_TREE_SRCU=y\nCONFIG_TASKS_RCU_GENERIC=y\nCONFIG_NEED_TASKS_RCU=y\nCONFIG_TASKS_RUDE_RCU=y\nCONFIG_TASKS_TRACE_RCU=y\nCONFIG_RCU_STALL_COMMON=y\nCONFIG_RCU_NEED_SEGCBLIST=y\n# end of RCU Subsystem\n\n# CONFIG_IKCONFIG is not set\n# CONFIG_IKHEADERS is not set\nCONFIG_LOG_BUF_SHIFT=18\nCONFIG_LOG_CPU_MAX_BUF_SHIFT=12\nCONFIG_PRINTK_INDEX=y\nCONFIG_HAVE_UNSTABLE_SCHED_CLOCK=y\n\n#\n# Scheduler features\n#\n# CONFIG_UCLAMP_TASK is not set\n# end of Scheduler features\n\nCONFIG_ARCH_SUPPORTS_NUMA_BALANCING=y\nCONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH=y\nCONFIG_CC_HAS_INT128=y\nCONFIG_CC_IMPLICIT_FALLTHROUGH=\"-Wimplicit-fallthrough\"\nCONFIG_GCC10_NO_ARRAY_BOUNDS=y\nCONFIG_GCC_NO_STRINGOP_OVERFLOW=y\nCONFIG_ARCH_SUPPORTS_INT128=y\n# CONFIG_NUMA_BALANCING is not set\nCONFIG_SLAB_OBJ_EXT=y\nCONFIG_CGROUPS=y\nCONFIG_PAGE_COUNTER=y\n# CONFIG_CGROUP_FAVOR_DYNMODS is not set\nCONFIG_MEMCG=y\n# CONFIG_MEMCG_V1 is not set\nCONFIG_BLK_CGROUP=y\nCONFIG_CGROUP_WRITEBACK=y\nCONFIG_CGROUP_SCHED=y\nCONFIG_GROUP_SCHED_WEIGHT=y\nCONFIG_GROUP_SCHED_BANDWIDTH=y\nCONFIG_FAIR_GROUP_SCHED=y\nCONFIG_CFS_BANDWIDTH=y\n# CONFIG_RT_GROUP_SCHED is not set\nCONFIG_EXT_GROUP_SCHED=y\nCONFIG_SCHED_MM_CID=y\nCONFIG_CGROUP_PIDS=y\n# CONFIG_CGROUP_RDMA is not set\n# CONFIG_CGROUP_DMEM is not set\nCONFIG_CGROUP_FREEZER=y\nCONFIG_CGROUP_HUGETLB=y\nCONFIG_CPUSETS=y\n# CONFIG_CPUSETS_V1 is not set\nCONFIG_CGROUP_DEVICE=y\nCONFIG_CGROUP_CPUACCT=y\nCONFIG_CGROUP_PERF=y\nCONFIG_CGROUP_BPF=y\n# CONFIG_CGROUP_MISC is not set\n# CONFIG_CGROUP_DEBUG is not set\nCONFIG_SOCK_CGROUP_DATA=y\nCONFIG_NAMESPACES=y\nCONFIG_UTS_NS=y\nCONFIG_TIME_NS=y\nCONFIG_IPC_NS=y\nCONFIG_USER_NS=y\nCONFIG_PID_NS=y\nCONFIG_NET_NS=y\n# CONFIG_CHECKPOINT_RESTORE is not set\n# CONFIG_SCHED_AUTOGROUP is not set\nCONFIG_RELAY=y\nCONFIG_BLK_DEV_INITRD=y\nCONFIG_INITRAMFS_SOURCE=\"\"\nCONFIG_RD_GZIP=y\nCONFIG_RD_BZIP2=y\nCONFIG_RD_LZMA=y\nCONFIG_RD_XZ=y\nCONFIG_RD_LZO=y\nCONFIG_RD_LZ4=y\nCONFIG_RD_ZSTD=y\n# CONFIG_BOOT_CONFIG is not set\nCONFIG_CMDLINE_LOG_WRAP_IDEAL_LEN=1021\nCONFIG_INITRAMFS_PRESERVE_MTIME=y\nCONFIG_CC_OPTIMIZE_FOR_PERFORMANCE=y\n# CONFIG_CC_OPTIMIZE_FOR_SIZE is not set\nCONFIG_LD_ORPHAN_WARN=y\nCONFIG_LD_ORPHAN_WARN_LEVEL=\"warn\"\nCONFIG_SYSCTL=y\nCONFIG_SYSCTL_EXCEPTION_TRACE=y\nCONFIG_SYSFS_SYSCALL=y\nCONFIG_HAVE_PCSPKR_PLATFORM=y\nCONFIG_EXPERT=y\nCONFIG_MULTIUSER=y\nCONFIG_SGETMASK_SYSCALL=y\nCONFIG_FHANDLE=y\nCONFIG_POSIX_TIMERS=y\nCONFIG_PRINTK=y\nCONFIG_BUG=y\nCONFIG_ELF_CORE=y\nCONFIG_PCSPKR_PLATFORM=y\n# CONFIG_BASE_SMALL is not set\nCONFIG_FUTEX=y\nCONFIG_FUTEX_PI=y\nCONFIG_FUTEX_PRIVATE_HASH=y\nCONFIG_FUTEX_MPOL=y\nCONFIG_EPOLL=y\nCONFIG_SIGNALFD=y\nCONFIG_TIMERFD=y\nCONFIG_EVENTFD=y\nCONFIG_SHMEM=y\nCONFIG_AIO=y\nCONFIG_IO_URING=y\n# CONFIG_IO_URING_MOCK_FILE is not set\nCONFIG_ADVISE_SYSCALLS=y\nCONFIG_MEMBARRIER=y\nCONFIG_KCMP=y\nCONFIG_RSEQ=y\n# CONFIG_RSEQ_STATS is not set\n# CONFIG_RSEQ_DEBUG_DEFAULT_ENABLE is not set\nCONFIG_CACHESTAT_SYSCALL=y\nCONFIG_KALLSYMS=y\n# CONFIG_KALLSYMS_SELFTEST is not set\nCONFIG_KALLSYMS_ALL=y\nCONFIG_ARCH_HAS_MEMBARRIER_SYNC_CORE=y\nCONFIG_ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS=y\nCONFIG_HAVE_PERF_EVENTS=y\n\n#\n# Kernel Performance Events And Counters\n#\nCONFIG_PERF_EVENTS=y\n# CONFIG_DEBUG_PERF_USE_VMALLOC is not set\n# end of Kernel Performance Events And Counters\n\nCONFIG_SYSTEM_DATA_VERIFICATION=y\nCONFIG_PROFILING=y\nCONFIG_TRACEPOINTS=y\n\n#\n# Kexec and crash features\n#\nCONFIG_CRASH_RESERVE=y\nCONFIG_VMCORE_INFO=y\nCONFIG_KEXEC_CORE=y\nCONFIG_KEXEC=y\n# CONFIG_KEXEC_FILE is not set\n# CONFIG_KEXEC_JUMP is not set\nCONFIG_CRASH_DUMP=y\nCONFIG_CRASH_HOTPLUG=y\nCONFIG_CRASH_MAX_MEMORY_RANGES=8192\n# end of Kexec and crash features\n\n#\n# Live Update and Kexec HandOver\n#\n# CONFIG_KEXEC_HANDOVER is not set\n# end of Live Update and Kexec HandOver\n# end of General setup\n\nCONFIG_64BIT=y\nCONFIG_X86_64=y\nCONFIG_X86=y\nCONFIG_INSTRUCTION_DECODER=y\nCONFIG_OUTPUT_FORMAT=\"elf64-x86-64\"\nCONFIG_LOCKDEP_SUPPORT=y\nCONFIG_STACKTRACE_SUPPORT=y\nCONFIG_MMU=y\nCONFIG_ARCH_MMAP_RND_BITS_MIN=28\nCONFIG_ARCH_MMAP_RND_BITS_MAX=32\nCONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN=8\nCONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX=16\nCONFIG_GENERIC_ISA_DMA=y\nCONFIG_GENERIC_BUG=y\nCONFIG_GENERIC_BUG_RELATIVE_POINTERS=y\nCONFIG_ARCH_MAY_HAVE_PC_FDC=y\nCONFIG_GENERIC_CALIBRATE_DELAY=y\nCONFIG_ARCH_HAS_CPU_RELAX=y\nCONFIG_ARCH_HIBERNATION_POSSIBLE=y\nCONFIG_ARCH_SUSPEND_POSSIBLE=y\nCONFIG_AUDIT_ARCH=y\nCONFIG_HAVE_INTEL_TXT=y\nCONFIG_ARCH_SUPPORTS_UPROBES=y\nCONFIG_FIX_EARLYCON_MEM=y\nCONFIG_PGTABLE_LEVELS=5\n\n#\n# Processor type and features\n#\nCONFIG_SMP=y\n# CONFIG_X86_X2APIC is not set\nCONFIG_X86_MPPARSE=y\n# CONFIG_X86_CPU_RESCTRL is not set\nCONFIG_X86_FRED=y\nCONFIG_X86_EXTENDED_PLATFORM=y\n# CONFIG_X86_VSMP is not set\n# CONFIG_X86_INTEL_MID is not set\n# CONFIG_X86_GOLDFISH is not set\nCONFIG_X86_INTEL_LPSS=y\n# CONFIG_X86_AMD_PLATFORM_DEVICE is not set\nCONFIG_IOSF_MBI=y\n# CONFIG_IOSF_MBI_DEBUG is not set\nCONFIG_X86_SUPPORTS_MEMORY_FAILURE=y\nCONFIG_SCHED_OMIT_FRAME_POINTER=y\nCONFIG_HYPERVISOR_GUEST=y\nCONFIG_PARAVIRT=y\nCONFIG_PARAVIRT_DEBUG=y\nCONFIG_PARAVIRT_SPINLOCKS=y\nCONFIG_X86_HV_CALLBACK_VECTOR=y\n# CONFIG_XEN is not set\nCONFIG_KVM_GUEST=y\nCONFIG_ARCH_CPUIDLE_HALTPOLL=y\n# CONFIG_PVH is not set\n# CONFIG_PARAVIRT_TIME_ACCOUNTING is not set\nCONFIG_PARAVIRT_CLOCK=y\n# CONFIG_JAILHOUSE_GUEST is not set\n# CONFIG_ACRN_GUEST is not set\n# CONFIG_BHYVE_GUEST is not set\nCONFIG_CC_HAS_MARCH_NATIVE=y\nCONFIG_X86_NATIVE_CPU=y\nCONFIG_X86_INTERNODE_CACHE_SHIFT=6\nCONFIG_X86_L1_CACHE_SHIFT=6\nCONFIG_X86_TSC=y\nCONFIG_X86_HAVE_PAE=y\nCONFIG_X86_CX8=y\nCONFIG_X86_CMOV=y\nCONFIG_X86_MINIMUM_CPU_FAMILY=64\nCONFIG_X86_DEBUGCTLMSR=y\nCONFIG_IA32_FEAT_CTL=y\nCONFIG_X86_VMX_FEATURE_NAMES=y\n# CONFIG_PROCESSOR_SELECT is not set\nCONFIG_BROADCAST_TLB_FLUSH=y\nCONFIG_CPU_SUP_INTEL=y\nCONFIG_CPU_SUP_AMD=y\nCONFIG_CPU_SUP_HYGON=y\nCONFIG_CPU_SUP_CENTAUR=y\nCONFIG_CPU_SUP_ZHAOXIN=y\nCONFIG_HPET_TIMER=y\nCONFIG_HPET_EMULATE_RTC=y\nCONFIG_DMI=y\n# CONFIG_GART_IOMMU is not set\nCONFIG_BOOT_VESA_SUPPORT=y\n# CONFIG_MAXSMP is not set\nCONFIG_NR_CPUS_RANGE_BEGIN=2\nCONFIG_NR_CPUS_RANGE_END=512\nCONFIG_NR_CPUS_DEFAULT=64\nCONFIG_NR_CPUS=64\nCONFIG_SCHED_MC_PRIO=y\nCONFIG_X86_LOCAL_APIC=y\nCONFIG_ACPI_MADT_WAKEUP=y\nCONFIG_X86_IO_APIC=y\nCONFIG_X86_REROUTE_FOR_BROKEN_BOOT_IRQS=y\nCONFIG_X86_MCE=y\n# CONFIG_X86_MCELOG_LEGACY is not set\nCONFIG_X86_MCE_INTEL=y\nCONFIG_X86_MCE_AMD=y\nCONFIG_X86_MCE_THRESHOLD=y\n# CONFIG_X86_MCE_INJECT is not set\n\n#\n# Performance monitoring\n#\nCONFIG_PERF_EVENTS_INTEL_UNCORE=y\nCONFIG_PERF_EVENTS_INTEL_RAPL=y\nCONFIG_PERF_EVENTS_INTEL_CSTATE=y\n# CONFIG_PERF_EVENTS_AMD_POWER is not set\nCONFIG_PERF_EVENTS_AMD_UNCORE=y\n# CONFIG_PERF_EVENTS_AMD_BRS is not set\n# end of Performance monitoring\n\nCONFIG_X86_16BIT=y\nCONFIG_X86_ESPFIX64=y\nCONFIG_X86_VSYSCALL_EMULATION=y\nCONFIG_X86_IOPL_IOPERM=y\nCONFIG_MICROCODE=y\n# CONFIG_MICROCODE_LATE_LOADING is not set\n# CONFIG_MICROCODE_DBG is not set\nCONFIG_X86_MSR=y\nCONFIG_X86_CPUID=y\nCONFIG_X86_DIRECT_GBPAGES=y\n# CONFIG_X86_CPA_STATISTICS is not set\nCONFIG_NUMA=y\nCONFIG_AMD_NUMA=y\nCONFIG_X86_64_ACPI_NUMA=y\nCONFIG_NODES_SHIFT=6\nCONFIG_ARCH_SPARSEMEM_ENABLE=y\nCONFIG_ARCH_SPARSEMEM_DEFAULT=y\nCONFIG_ARCH_PROC_KCORE_TEXT=y\nCONFIG_ILLEGAL_POINTER_VALUE=0xdead000000000000\n# CONFIG_X86_PMEM_LEGACY is not set\nCONFIG_X86_CHECK_BIOS_CORRUPTION=y\nCONFIG_X86_BOOTPARAM_MEMORY_CORRUPTION_CHECK=y\nCONFIG_MTRR=y\n# CONFIG_MTRR_SANITIZER is not set\nCONFIG_X86_PAT=y\nCONFIG_X86_UMIP=y\nCONFIG_CC_HAS_IBT=y\n# CONFIG_X86_KERNEL_IBT is not set\nCONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS=y\nCONFIG_ARCH_PKEY_BITS=4\nCONFIG_X86_INTEL_TSX_MODE_OFF=y\n# CONFIG_X86_INTEL_TSX_MODE_ON is not set\n# CONFIG_X86_INTEL_TSX_MODE_AUTO is not set\n# CONFIG_X86_USER_SHADOW_STACK is not set\nCONFIG_EFI=y\n# CONFIG_EFI_STUB is not set\nCONFIG_EFI_RUNTIME_MAP=y\n# CONFIG_HZ_100 is not set\n# CONFIG_HZ_250 is not set\n# CONFIG_HZ_300 is not set\nCONFIG_HZ_1000=y\nCONFIG_HZ=1000\nCONFIG_SCHED_HRTICK=y\nCONFIG_ARCH_SUPPORTS_KEXEC=y\nCONFIG_ARCH_SUPPORTS_KEXEC_FILE=y\nCONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY=y\nCONFIG_ARCH_SUPPORTS_KEXEC_SIG=y\nCONFIG_ARCH_SUPPORTS_KEXEC_SIG_FORCE=y\nCONFIG_ARCH_SUPPORTS_KEXEC_BZIMAGE_VERIFY_SIG=y\nCONFIG_ARCH_SUPPORTS_KEXEC_JUMP=y\nCONFIG_ARCH_SUPPORTS_KEXEC_HANDOVER=y\nCONFIG_ARCH_SUPPORTS_CRASH_DUMP=y\nCONFIG_ARCH_DEFAULT_CRASH_DUMP=y\nCONFIG_ARCH_SUPPORTS_CRASH_HOTPLUG=y\nCONFIG_ARCH_HAS_GENERIC_CRASHKERNEL_RESERVATION=y\nCONFIG_PHYSICAL_START=0x1000000\nCONFIG_RELOCATABLE=y\n# CONFIG_RANDOMIZE_BASE is not set\nCONFIG_PHYSICAL_ALIGN=0x200000\n# CONFIG_ADDRESS_MASKING is not set\nCONFIG_HOTPLUG_CPU=y\nCONFIG_LEGACY_VSYSCALL_XONLY=y\n# CONFIG_LEGACY_VSYSCALL_NONE is not set\n# CONFIG_CMDLINE_BOOL is not set\nCONFIG_MODIFY_LDT_SYSCALL=y\n# CONFIG_STRICT_SIGALTSTACK_SIZE is not set\nCONFIG_HAVE_LIVEPATCH=y\n# CONFIG_LIVEPATCH is not set\nCONFIG_HAVE_KLP_BUILD=y\nCONFIG_X86_BUS_LOCK_DETECT=y\n# end of Processor type and features\n\nCONFIG_CC_HAS_NAMED_AS_FIXED_SANITIZERS=y\nCONFIG_CC_HAS_SLS=y\nCONFIG_CC_HAS_RETURN_THUNK=y\nCONFIG_CC_HAS_ENTRY_PADDING=y\nCONFIG_CC_HAS_KCFI_ARITY=y\nCONFIG_FUNCTION_PADDING_CFI=11\nCONFIG_FUNCTION_PADDING_BYTES=11\n# CONFIG_CPU_MITIGATIONS is not set\nCONFIG_ARCH_HAS_ADD_PAGES=y\n\n#\n# Power management and ACPI options\n#\nCONFIG_ARCH_HIBERNATION_HEADER=y\nCONFIG_SUSPEND=y\nCONFIG_SUSPEND_FREEZER=y\n# CONFIG_SUSPEND_SKIP_SYNC is not set\nCONFIG_HIBERNATE_CALLBACKS=y\nCONFIG_HIBERNATION=y\nCONFIG_HIBERNATION_SNAPSHOT_DEV=y\nCONFIG_HIBERNATION_COMP_LZO=y\nCONFIG_HIBERNATION_DEF_COMP=\"lzo\"\nCONFIG_PM_STD_PARTITION=\"\"\nCONFIG_PM_SLEEP=y\nCONFIG_PM_SLEEP_SMP=y\n# CONFIG_PM_AUTOSLEEP is not set\n# CONFIG_PM_USERSPACE_AUTOSLEEP is not set\n# CONFIG_PM_WAKELOCKS is not set\n# CONFIG_PM_QOS_CPU_SYSTEM_WAKEUP is not set\nCONFIG_PM=y\nCONFIG_PM_DEBUG=y\n# CONFIG_PM_ADVANCED_DEBUG is not set\n# CONFIG_PM_TEST_SUSPEND is not set\nCONFIG_PM_SLEEP_DEBUG=y\nCONFIG_PM_TRACE=y\nCONFIG_PM_TRACE_RTC=y\nCONFIG_PM_CLK=y\n# CONFIG_WQ_POWER_EFFICIENT_DEFAULT is not set\n# CONFIG_ENERGY_MODEL is not set\nCONFIG_ARCH_SUPPORTS_ACPI=y\nCONFIG_ACPI=y\nCONFIG_ACPI_LEGACY_TABLES_LOOKUP=y\nCONFIG_ARCH_MIGHT_HAVE_ACPI_PDC=y\nCONFIG_ACPI_SYSTEM_POWER_STATES_SUPPORT=y\nCONFIG_ACPI_THERMAL_LIB=y\n# CONFIG_ACPI_DEBUGGER is not set\nCONFIG_ACPI_SPCR_TABLE=y\n# CONFIG_ACPI_FPDT is not set\nCONFIG_ACPI_LPIT=y\nCONFIG_ACPI_SLEEP=y\nCONFIG_ACPI_REV_OVERRIDE_POSSIBLE=y\nCONFIG_ACPI_EC=y\n# CONFIG_ACPI_EC_DEBUGFS is not set\nCONFIG_ACPI_AC=y\nCONFIG_ACPI_BATTERY=y\nCONFIG_ACPI_BUTTON=y\nCONFIG_ACPI_FAN=y\n# CONFIG_ACPI_TAD is not set\nCONFIG_ACPI_DOCK=y\nCONFIG_ACPI_CPU_FREQ_PSS=y\nCONFIG_ACPI_PROCESSOR_CSTATE=y\nCONFIG_ACPI_PROCESSOR_IDLE=y\nCONFIG_ACPI_CPPC_LIB=y\nCONFIG_ACPI_PROCESSOR=y\nCONFIG_ACPI_HOTPLUG_CPU=y\n# CONFIG_ACPI_PROCESSOR_AGGREGATOR is not set\nCONFIG_ACPI_THERMAL=y\nCONFIG_ARCH_HAS_ACPI_TABLE_UPGRADE=y\nCONFIG_ACPI_TABLE_UPGRADE=y\n# CONFIG_ACPI_DEBUG is not set\n# CONFIG_ACPI_PCI_SLOT is not set\nCONFIG_ACPI_CONTAINER=y\nCONFIG_ACPI_HOTPLUG_IOAPIC=y\n# CONFIG_ACPI_SBS is not set\n# CONFIG_ACPI_HED is not set\nCONFIG_ACPI_BGRT=y\n# CONFIG_ACPI_REDUCED_HARDWARE_ONLY is not set\n# CONFIG_ACPI_NFIT is not set\nCONFIG_ACPI_NUMA=y\n# CONFIG_ACPI_HMAT is not set\nCONFIG_HAVE_ACPI_APEI=y\nCONFIG_HAVE_ACPI_APEI_NMI=y\n# CONFIG_ACPI_APEI is not set\n# CONFIG_ACPI_DPTF is not set\n# CONFIG_ACPI_EXTLOG is not set\n# CONFIG_ACPI_CONFIGFS is not set\n# CONFIG_ACPI_PFRUT is not set\n# CONFIG_ACPI_PCC is not set\n# CONFIG_ACPI_FFH is not set\nCONFIG_ACPI_MRRM=y\n# CONFIG_PMIC_OPREGION is not set\nCONFIG_ACPI_PRMT=y\nCONFIG_X86_PM_TIMER=y\n\n#\n# CPU Frequency scaling\n#\nCONFIG_CPU_FREQ=y\nCONFIG_CPU_FREQ_GOV_ATTR_SET=y\nCONFIG_CPU_FREQ_GOV_COMMON=y\nCONFIG_CPU_FREQ_STAT=y\nCONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE=y\n# CONFIG_CPU_FREQ_DEFAULT_GOV_POWERSAVE is not set\n# CONFIG_CPU_FREQ_DEFAULT_GOV_USERSPACE is not set\n# CONFIG_CPU_FREQ_DEFAULT_GOV_SCHEDUTIL is not set\nCONFIG_CPU_FREQ_GOV_PERFORMANCE=y\n# CONFIG_CPU_FREQ_GOV_POWERSAVE is not set\nCONFIG_CPU_FREQ_GOV_USERSPACE=y\nCONFIG_CPU_FREQ_GOV_ONDEMAND=y\n# CONFIG_CPU_FREQ_GOV_CONSERVATIVE is not set\nCONFIG_CPU_FREQ_GOV_SCHEDUTIL=y\n\n#\n# CPU frequency scaling drivers\n#\nCONFIG_X86_INTEL_PSTATE=y\nCONFIG_X86_PCC_CPUFREQ=y\nCONFIG_X86_AMD_PSTATE=y\nCONFIG_X86_AMD_PSTATE_DEFAULT_MODE=3\n# CONFIG_X86_AMD_PSTATE_UT is not set\nCONFIG_X86_ACPI_CPUFREQ=y\nCONFIG_X86_ACPI_CPUFREQ_CPB=y\n# CONFIG_X86_POWERNOW_K8 is not set\n# CONFIG_X86_AMD_FREQ_SENSITIVITY is not set\n# CONFIG_X86_SPEEDSTEP_CENTRINO is not set\n# CONFIG_X86_P4_CLOCKMOD is not set\n\n#\n# shared options\n#\nCONFIG_CPUFREQ_ARCH_CUR_FREQ=y\n# end of CPU Frequency scaling\n\n#\n# CPU Idle\n#\nCONFIG_CPU_IDLE=y\n# CONFIG_CPU_IDLE_GOV_LADDER is not set\nCONFIG_CPU_IDLE_GOV_MENU=y\n# CONFIG_CPU_IDLE_GOV_TEO is not set\nCONFIG_CPU_IDLE_GOV_HALTPOLL=y\nCONFIG_HALTPOLL_CPUIDLE=y\n# end of CPU Idle\n\n# CONFIG_INTEL_IDLE is not set\n# end of Power management and ACPI options\n\n#\n# Bus options (PCI etc.)\n#\nCONFIG_PCI_DIRECT=y\nCONFIG_PCI_MMCONFIG=y\nCONFIG_MMCONF_FAM10H=y\n# CONFIG_ISA_BUS is not set\nCONFIG_ISA_DMA_API=y\nCONFIG_AMD_NB=y\nCONFIG_AMD_NODE=y\n# end of Bus options (PCI etc.)\n\n#\n# Binary Emulations\n#\n# CONFIG_IA32_EMULATION is not set\n# end of Binary Emulations\n\n# CONFIG_VIRTUALIZATION is not set\nCONFIG_X86_REQUIRED_FEATURE_ALWAYS=y\nCONFIG_X86_REQUIRED_FEATURE_NOPL=y\nCONFIG_X86_REQUIRED_FEATURE_CX8=y\nCONFIG_X86_REQUIRED_FEATURE_CMOV=y\nCONFIG_X86_REQUIRED_FEATURE_CPUID=y\nCONFIG_X86_REQUIRED_FEATURE_FPU=y\nCONFIG_X86_REQUIRED_FEATURE_PAE=y\nCONFIG_X86_REQUIRED_FEATURE_PSE=y\nCONFIG_X86_REQUIRED_FEATURE_PGE=y\nCONFIG_X86_REQUIRED_FEATURE_MSR=y\nCONFIG_X86_REQUIRED_FEATURE_FXSR=y\nCONFIG_X86_REQUIRED_FEATURE_XMM=y\nCONFIG_X86_REQUIRED_FEATURE_XMM2=y\nCONFIG_X86_REQUIRED_FEATURE_LM=y\nCONFIG_X86_DISABLED_FEATURE_VME=y\nCONFIG_X86_DISABLED_FEATURE_K6_MTRR=y\nCONFIG_X86_DISABLED_FEATURE_CYRIX_ARR=y\nCONFIG_X86_DISABLED_FEATURE_CENTAUR_MCR=y\nCONFIG_X86_DISABLED_FEATURE_PTI=y\nCONFIG_X86_DISABLED_FEATURE_RETPOLINE=y\nCONFIG_X86_DISABLED_FEATURE_RETPOLINE_LFENCE=y\nCONFIG_X86_DISABLED_FEATURE_RETHUNK=y\nCONFIG_X86_DISABLED_FEATURE_UNRET=y\nCONFIG_X86_DISABLED_FEATURE_CALL_DEPTH=y\nCONFIG_X86_DISABLED_FEATURE_LAM=y\nCONFIG_X86_DISABLED_FEATURE_ENQCMD=y\nCONFIG_X86_DISABLED_FEATURE_SGX=y\nCONFIG_X86_DISABLED_FEATURE_XENPV=y\nCONFIG_X86_DISABLED_FEATURE_TDX_GUEST=y\nCONFIG_X86_DISABLED_FEATURE_USER_SHSTK=y\nCONFIG_X86_DISABLED_FEATURE_IBT=y\nCONFIG_X86_DISABLED_FEATURE_SEV_SNP=y\nCONFIG_AS_WRUSS=y\nCONFIG_ARCH_CONFIGURES_CPU_MITIGATIONS=y\n\n#\n# General architecture-dependent options\n#\nCONFIG_HOTPLUG_SMT=y\nCONFIG_ARCH_SUPPORTS_SCHED_SMT=y\nCONFIG_ARCH_SUPPORTS_SCHED_CLUSTER=y\nCONFIG_ARCH_SUPPORTS_SCHED_MC=y\nCONFIG_SCHED_SMT=y\nCONFIG_SCHED_CLUSTER=y\nCONFIG_SCHED_MC=y\nCONFIG_HOTPLUG_CORE_SYNC=y\nCONFIG_HOTPLUG_CORE_SYNC_DEAD=y\nCONFIG_HOTPLUG_CORE_SYNC_FULL=y\nCONFIG_HOTPLUG_SPLIT_STARTUP=y\nCONFIG_HOTPLUG_PARALLEL=y\nCONFIG_GENERIC_IRQ_ENTRY=y\nCONFIG_GENERIC_SYSCALL=y\nCONFIG_GENERIC_ENTRY=y\nCONFIG_KPROBES=y\nCONFIG_JUMP_LABEL=y\n# CONFIG_STATIC_KEYS_SELFTEST is not set\n# CONFIG_STATIC_CALL_SELFTEST is not set\nCONFIG_OPTPROBES=y\nCONFIG_KPROBES_ON_FTRACE=y\nCONFIG_UPROBES=y\nCONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS=y\nCONFIG_ARCH_USE_BUILTIN_BSWAP=y\nCONFIG_KRETPROBES=y\nCONFIG_KRETPROBE_ON_RETHOOK=y\nCONFIG_HAVE_IOREMAP_PROT=y\nCONFIG_HAVE_KPROBES=y\nCONFIG_HAVE_KRETPROBES=y\nCONFIG_HAVE_OPTPROBES=y\nCONFIG_HAVE_KPROBES_ON_FTRACE=y\nCONFIG_ARCH_CORRECT_STACKTRACE_ON_KRETPROBE=y\nCONFIG_HAVE_FUNCTION_ERROR_INJECTION=y\nCONFIG_HAVE_NMI=y\nCONFIG_TRACE_IRQFLAGS_SUPPORT=y\nCONFIG_TRACE_IRQFLAGS_NMI_SUPPORT=y\nCONFIG_HAVE_ARCH_TRACEHOOK=y\nCONFIG_HAVE_DMA_CONTIGUOUS=y\nCONFIG_GENERIC_SMP_IDLE_THREAD=y\nCONFIG_ARCH_HAS_FORTIFY_SOURCE=y\nCONFIG_ARCH_HAS_SET_MEMORY=y\nCONFIG_ARCH_HAS_SET_DIRECT_MAP=y\nCONFIG_ARCH_HAS_CPU_FINALIZE_INIT=y\nCONFIG_ARCH_HAS_CPU_PASID=y\nCONFIG_HAVE_ARCH_THREAD_STRUCT_WHITELIST=y\nCONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT=y\nCONFIG_ARCH_WANTS_NO_INSTR=y\nCONFIG_HAVE_ASM_MODVERSIONS=y\nCONFIG_HAVE_REGS_AND_STACK_ACCESS_API=y\nCONFIG_HAVE_RSEQ=y\nCONFIG_HAVE_RUST=y\nCONFIG_HAVE_FUNCTION_ARG_ACCESS_API=y\nCONFIG_HAVE_HW_BREAKPOINT=y\nCONFIG_HAVE_MIXED_BREAKPOINTS_REGS=y\nCONFIG_HAVE_USER_RETURN_NOTIFIER=y\nCONFIG_HAVE_PERF_EVENTS_NMI=y\nCONFIG_HAVE_HARDLOCKUP_DETECTOR_PERF=y\nCONFIG_UNWIND_USER=y\nCONFIG_HAVE_UNWIND_USER_FP=y\nCONFIG_HAVE_PERF_REGS=y\nCONFIG_HAVE_PERF_USER_STACK_DUMP=y\nCONFIG_HAVE_ARCH_JUMP_LABEL=y\nCONFIG_HAVE_ARCH_JUMP_LABEL_RELATIVE=y\nCONFIG_MMU_GATHER_TABLE_FREE=y\nCONFIG_MMU_GATHER_RCU_TABLE_FREE=y\nCONFIG_MMU_GATHER_MERGE_VMAS=y\nCONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM=y\nCONFIG_MMU_LAZY_TLB_REFCOUNT=y\nCONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG=y\nCONFIG_ARCH_HAVE_EXTRA_ELF_NOTES=y\nCONFIG_ARCH_HAS_NMI_SAFE_THIS_CPU_OPS=y\nCONFIG_HAVE_ALIGNED_STRUCT_PAGE=y\nCONFIG_HAVE_CMPXCHG_LOCAL=y\nCONFIG_HAVE_CMPXCHG_DOUBLE=y\nCONFIG_HAVE_ARCH_SECCOMP=y\nCONFIG_HAVE_ARCH_SECCOMP_FILTER=y\nCONFIG_SECCOMP=y\nCONFIG_SECCOMP_FILTER=y\n# CONFIG_SECCOMP_CACHE_DEBUG is not set\nCONFIG_HAVE_ARCH_KSTACK_ERASE=y\nCONFIG_HAVE_STACKPROTECTOR=y\nCONFIG_STACKPROTECTOR=y\nCONFIG_STACKPROTECTOR_STRONG=y\nCONFIG_LTO=y\nCONFIG_LTO_CLANG=y\nCONFIG_ARCH_SUPPORTS_LTO_CLANG=y\nCONFIG_ARCH_SUPPORTS_LTO_CLANG_THIN=y\nCONFIG_HAS_LTO_CLANG=y\n# CONFIG_LTO_NONE is not set\n# CONFIG_LTO_CLANG_FULL is not set\nCONFIG_LTO_CLANG_THIN=y\nCONFIG_ARCH_SUPPORTS_AUTOFDO_CLANG=y\n# CONFIG_AUTOFDO_CLANG is not set\nCONFIG_ARCH_SUPPORTS_PROPELLER_CLANG=y\n# CONFIG_PROPELLER_CLANG is not set\nCONFIG_ARCH_SUPPORTS_CFI=y\nCONFIG_ARCH_USES_CFI_TRAPS=y\nCONFIG_CFI=y\nCONFIG_CFI_ICALL_NORMALIZE_INTEGERS=y\nCONFIG_HAVE_CFI_ICALL_NORMALIZE_INTEGERS=y\nCONFIG_HAVE_CFI_ICALL_NORMALIZE_INTEGERS_RUSTC=y\n# CONFIG_CFI_PERMISSIVE is not set\nCONFIG_HAVE_ARCH_WITHIN_STACK_FRAMES=y\nCONFIG_HAVE_CONTEXT_TRACKING_USER=y\nCONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK=y\nCONFIG_HAVE_VIRT_CPU_ACCOUNTING_GEN=y\nCONFIG_HAVE_IRQ_TIME_ACCOUNTING=y\nCONFIG_HAVE_MOVE_PUD=y\nCONFIG_HAVE_MOVE_PMD=y\nCONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE=y\nCONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD=y\nCONFIG_HAVE_ARCH_HUGE_VMAP=y\nCONFIG_HAVE_ARCH_HUGE_VMALLOC=y\nCONFIG_ARCH_WANT_HUGE_PMD_SHARE=y\nCONFIG_HAVE_ARCH_SOFT_DIRTY=y\nCONFIG_HAVE_MOD_ARCH_SPECIFIC=y\nCONFIG_MODULES_USE_ELF_RELA=y\nCONFIG_ARCH_HAS_EXECMEM_ROX=y\nCONFIG_HAVE_IRQ_EXIT_ON_IRQ_STACK=y\nCONFIG_HAVE_SOFTIRQ_ON_OWN_STACK=y\nCONFIG_SOFTIRQ_ON_OWN_STACK=y\nCONFIG_ARCH_HAS_ELF_RANDOMIZE=y\nCONFIG_HAVE_ARCH_MMAP_RND_BITS=y\nCONFIG_HAVE_EXIT_THREAD=y\nCONFIG_ARCH_MMAP_RND_BITS=28\nCONFIG_HAVE_PAGE_SIZE_4KB=y\nCONFIG_PAGE_SIZE_4KB=y\nCONFIG_PAGE_SIZE_LESS_THAN_64KB=y\nCONFIG_PAGE_SIZE_LESS_THAN_256KB=y\nCONFIG_PAGE_SHIFT=12\nCONFIG_HAVE_OBJTOOL=y\nCONFIG_HAVE_JUMP_LABEL_HACK=y\nCONFIG_HAVE_NOINSTR_HACK=y\nCONFIG_HAVE_NOINSTR_VALIDATION=y\nCONFIG_HAVE_UACCESS_VALIDATION=y\nCONFIG_HAVE_STACK_VALIDATION=y\nCONFIG_HAVE_RELIABLE_STACKTRACE=y\n# CONFIG_COMPAT_32BIT_TIME is not set\nCONFIG_ARCH_SUPPORTS_RT=y\nCONFIG_HAVE_ARCH_VMAP_STACK=y\nCONFIG_VMAP_STACK=y\nCONFIG_HAVE_ARCH_RANDOMIZE_KSTACK_OFFSET=y\n# CONFIG_RANDOMIZE_KSTACK_OFFSET is not set\nCONFIG_ARCH_HAS_STRICT_KERNEL_RWX=y\nCONFIG_STRICT_KERNEL_RWX=y\nCONFIG_ARCH_HAS_STRICT_MODULE_RWX=y\nCONFIG_STRICT_MODULE_RWX=y\nCONFIG_HAVE_ARCH_PREL32_RELOCATIONS=y\nCONFIG_ARCH_USE_MEMREMAP_PROT=y\n# CONFIG_LOCK_EVENT_COUNTS is not set\nCONFIG_ARCH_HAS_MEM_ENCRYPT=y\nCONFIG_HAVE_STATIC_CALL=y\nCONFIG_HAVE_STATIC_CALL_INLINE=y\nCONFIG_HAVE_PREEMPT_DYNAMIC=y\nCONFIG_HAVE_PREEMPT_DYNAMIC_CALL=y\nCONFIG_ARCH_WANT_LD_ORPHAN_WARN=y\nCONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC=y\nCONFIG_ARCH_SUPPORTS_PAGE_TABLE_CHECK=y\nCONFIG_ARCH_HAS_ELFCORE_COMPAT=y\nCONFIG_ARCH_HAS_PARANOID_L1D_FLUSH=y\nCONFIG_DYNAMIC_SIGFRAME=y\nCONFIG_ARCH_HAS_HW_PTE_YOUNG=y\nCONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG=y\nCONFIG_ARCH_HAS_KERNEL_FPU_SUPPORT=y\nCONFIG_HAVE_GENERIC_TIF_BITS=y\n\n#\n# GCOV-based kernel profiling\n#\n# CONFIG_GCOV_KERNEL is not set\nCONFIG_ARCH_HAS_GCOV_PROFILE_ALL=y\n# end of GCOV-based kernel profiling\n\nCONFIG_HAVE_GCC_PLUGINS=y\nCONFIG_FUNCTION_ALIGNMENT_4B=y\nCONFIG_FUNCTION_ALIGNMENT_16B=y\nCONFIG_FUNCTION_ALIGNMENT=16\nCONFIG_CC_HAS_SANE_FUNCTION_ALIGNMENT=y\n# end of General architecture-dependent options\n\nCONFIG_RT_MUTEXES=y\nCONFIG_MODULES=y\n# CONFIG_MODULE_DEBUG is not set\n# CONFIG_MODULE_FORCE_LOAD is not set\nCONFIG_MODULE_UNLOAD=y\nCONFIG_MODULE_FORCE_UNLOAD=y\n# CONFIG_MODULE_UNLOAD_TAINT_TRACKING is not set\nCONFIG_MODVERSIONS=y\nCONFIG_GENKSYMS=y\nCONFIG_ASM_MODVERSIONS=y\n# CONFIG_EXTENDED_MODVERSIONS is not set\nCONFIG_BASIC_MODVERSIONS=y\n# CONFIG_MODULE_SRCVERSION_ALL is not set\n# CONFIG_MODULE_SIG is not set\nCONFIG_MODULE_COMPRESS=y\n# CONFIG_MODULE_COMPRESS_GZIP is not set\n# CONFIG_MODULE_COMPRESS_XZ is not set\nCONFIG_MODULE_COMPRESS_ZSTD=y\nCONFIG_MODULE_COMPRESS_ALL=y\nCONFIG_MODULE_DECOMPRESS=y\n# CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS is not set\nCONFIG_MODPROBE_PATH=\"/sbin/modprobe\"\n# CONFIG_TRIM_UNUSED_KSYMS is not set\nCONFIG_MODULES_TREE_LOOKUP=y\nCONFIG_BLOCK=y\nCONFIG_BLOCK_LEGACY_AUTOLOAD=y\nCONFIG_BLK_CGROUP_RWSTAT=y\nCONFIG_BLK_DEV_BSG_COMMON=y\n# CONFIG_BLK_DEV_BSGLIB is not set\n# CONFIG_BLK_DEV_INTEGRITY is not set\nCONFIG_BLK_DEV_WRITE_MOUNTED=y\n# CONFIG_BLK_DEV_ZONED is not set\nCONFIG_BLK_DEV_THROTTLING=y\n# CONFIG_BLK_WBT is not set\n# CONFIG_BLK_CGROUP_IOLATENCY is not set\n# CONFIG_BLK_CGROUP_IOCOST is not set\n# CONFIG_BLK_CGROUP_IOPRIO is not set\nCONFIG_BLK_DEBUG_FS=y\n# CONFIG_BLK_SED_OPAL is not set\n# CONFIG_BLK_INLINE_ENCRYPTION is not set\n\n#\n# Partition Types\n#\nCONFIG_PARTITION_ADVANCED=y\n# CONFIG_ACORN_PARTITION is not set\n# CONFIG_AIX_PARTITION is not set\n# CONFIG_OSF_PARTITION is not set\n# CONFIG_AMIGA_PARTITION is not set\n# CONFIG_ATARI_PARTITION is not set\n# CONFIG_MAC_PARTITION is not set\nCONFIG_MSDOS_PARTITION=y\n# CONFIG_BSD_DISKLABEL is not set\n# CONFIG_MINIX_SUBPARTITION is not set\n# CONFIG_SOLARIS_X86_PARTITION is not set\n# CONFIG_UNIXWARE_DISKLABEL is not set\n# CONFIG_LDM_PARTITION is not set\n# CONFIG_SGI_PARTITION is not set\n# CONFIG_ULTRIX_PARTITION is not set\n# CONFIG_SUN_PARTITION is not set\n# CONFIG_KARMA_PARTITION is not set\nCONFIG_EFI_PARTITION=y\n# CONFIG_SYSV68_PARTITION is not set\n# CONFIG_CMDLINE_PARTITION is not set\n# end of Partition Types\n\nCONFIG_BLK_PM=y\nCONFIG_BLOCK_HOLDER_DEPRECATED=y\nCONFIG_BLK_MQ_STACKING=y\n\n#\n# IO Schedulers\n#\nCONFIG_MQ_IOSCHED_DEADLINE=y\nCONFIG_MQ_IOSCHED_KYBER=y\n# CONFIG_IOSCHED_BFQ is not set\n# end of IO Schedulers\n\nCONFIG_PADATA=y\nCONFIG_ASN1=y\nCONFIG_INLINE_SPIN_UNLOCK_IRQ=y\nCONFIG_INLINE_READ_UNLOCK=y\nCONFIG_INLINE_READ_UNLOCK_IRQ=y\nCONFIG_INLINE_WRITE_UNLOCK=y\nCONFIG_INLINE_WRITE_UNLOCK_IRQ=y\nCONFIG_ARCH_SUPPORTS_ATOMIC_RMW=y\nCONFIG_MUTEX_SPIN_ON_OWNER=y\nCONFIG_RWSEM_SPIN_ON_OWNER=y\nCONFIG_LOCK_SPIN_ON_OWNER=y\nCONFIG_ARCH_USE_QUEUED_SPINLOCKS=y\nCONFIG_QUEUED_SPINLOCKS=y\nCONFIG_ARCH_USE_QUEUED_RWLOCKS=y\nCONFIG_QUEUED_RWLOCKS=y\nCONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE=y\nCONFIG_ARCH_HAS_SYNC_CORE_BEFORE_USERMODE=y\nCONFIG_ARCH_HAS_SYSCALL_WRAPPER=y\nCONFIG_FREEZER=y\n\n#\n# Executable file formats\n#\nCONFIG_BINFMT_ELF=y\nCONFIG_ELFCORE=y\nCONFIG_CORE_DUMP_DEFAULT_ELF_HEADERS=y\nCONFIG_BINFMT_SCRIPT=y\nCONFIG_BINFMT_MISC=y\nCONFIG_COREDUMP=y\n# end of Executable file formats\n\n#\n# Memory Management options\n#\nCONFIG_SWAP=y\n# CONFIG_ZSWAP is not set\n\n#\n# Slab allocator options\n#\nCONFIG_SLUB=y\nCONFIG_KVFREE_RCU_BATCHED=y\n# CONFIG_SLUB_TINY is not set\nCONFIG_SLAB_MERGE_DEFAULT=y\n# CONFIG_SLAB_FREELIST_RANDOM is not set\n# CONFIG_SLAB_FREELIST_HARDENED is not set\n# CONFIG_SLAB_BUCKETS is not set\n# CONFIG_SLUB_STATS is not set\nCONFIG_SLUB_CPU_PARTIAL=y\n# CONFIG_RANDOM_KMALLOC_CACHES is not set\n# end of Slab allocator options\n\n# CONFIG_SHUFFLE_PAGE_ALLOCATOR is not set\n# CONFIG_COMPAT_BRK is not set\nCONFIG_SPARSEMEM=y\nCONFIG_SPARSEMEM_EXTREME=y\nCONFIG_SPARSEMEM_VMEMMAP_ENABLE=y\nCONFIG_SPARSEMEM_VMEMMAP=y\nCONFIG_SPARSEMEM_VMEMMAP_PREINIT=y\nCONFIG_ARCH_WANT_OPTIMIZE_DAX_VMEMMAP=y\nCONFIG_ARCH_WANT_OPTIMIZE_HUGETLB_VMEMMAP=y\nCONFIG_ARCH_WANT_HUGETLB_VMEMMAP_PREINIT=y\nCONFIG_HAVE_GUP_FAST=y\nCONFIG_EXCLUSIVE_SYSTEM_RAM=y\nCONFIG_ARCH_ENABLE_MEMORY_HOTPLUG=y\n# CONFIG_MEMORY_HOTPLUG is not set\nCONFIG_ARCH_MHP_MEMMAP_ON_MEMORY_ENABLE=y\nCONFIG_SPLIT_PTE_PTLOCKS=y\nCONFIG_ARCH_ENABLE_SPLIT_PMD_PTLOCK=y\nCONFIG_SPLIT_PMD_PTLOCKS=y\nCONFIG_COMPACTION=y\nCONFIG_COMPACT_UNEVICTABLE_DEFAULT=1\n# CONFIG_PAGE_REPORTING is not set\nCONFIG_MIGRATION=y\nCONFIG_ARCH_ENABLE_HUGEPAGE_MIGRATION=y\nCONFIG_PCP_BATCH_SCALE_MAX=5\nCONFIG_PHYS_ADDR_T_64BIT=y\nCONFIG_MMU_NOTIFIER=y\n# CONFIG_KSM is not set\nCONFIG_DEFAULT_MMAP_MIN_ADDR=4096\nCONFIG_ARCH_SUPPORTS_MEMORY_FAILURE=y\n# CONFIG_MEMORY_FAILURE is not set\nCONFIG_ARCH_WANT_GENERAL_HUGETLB=y\nCONFIG_ARCH_WANTS_THP_SWAP=y\n# CONFIG_TRANSPARENT_HUGEPAGE is not set\nCONFIG_PAGE_MAPCOUNT=y\nCONFIG_PGTABLE_HAS_HUGE_LEAVES=y\nCONFIG_HAVE_GIGANTIC_FOLIOS=y\nCONFIG_ASYNC_KERNEL_PGTABLE_FREE=y\nCONFIG_NEED_PER_CPU_EMBED_FIRST_CHUNK=y\nCONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK=y\nCONFIG_USE_PERCPU_NUMA_NODE_ID=y\nCONFIG_HAVE_SETUP_PER_CPU_AREA=y\n# CONFIG_CMA is not set\nCONFIG_PAGE_BLOCK_MAX_ORDER=10\nCONFIG_GENERIC_EARLY_IOREMAP=y\n# CONFIG_DEFERRED_STRUCT_PAGE_INIT is not set\n# CONFIG_IDLE_PAGE_TRACKING is not set\nCONFIG_ARCH_HAS_CACHE_LINE_SIZE=y\nCONFIG_ARCH_HAS_CURRENT_STACK_POINTER=y\nCONFIG_ARCH_HAS_ZONE_DMA_SET=y\nCONFIG_ZONE_DMA=y\nCONFIG_ZONE_DMA32=y\nCONFIG_ARCH_USES_HIGH_VMA_FLAGS=y\nCONFIG_ARCH_HAS_PKEYS=y\nCONFIG_ARCH_USES_PG_ARCH_2=y\nCONFIG_VM_EVENT_COUNTERS=y\n# CONFIG_PERCPU_STATS is not set\n# CONFIG_GUP_TEST is not set\n# CONFIG_DMAPOOL_TEST is not set\nCONFIG_ARCH_HAS_PTE_SPECIAL=y\nCONFIG_MEMFD_CREATE=y\nCONFIG_SECRETMEM=y\n# CONFIG_ANON_VMA_NAME is not set\n# CONFIG_USERFAULTFD is not set\n# CONFIG_LRU_GEN is not set\nCONFIG_ARCH_SUPPORTS_PER_VMA_LOCK=y\nCONFIG_PER_VMA_LOCK=y\nCONFIG_LOCK_MM_AND_FIND_VMA=y\nCONFIG_IOMMU_MM_DATA=y\nCONFIG_EXECMEM=y\nCONFIG_NUMA_MEMBLKS=y\n# CONFIG_NUMA_EMU is not set\nCONFIG_ARCH_SUPPORTS_PT_RECLAIM=y\nCONFIG_PT_RECLAIM=y\n\n#\n# Data Access Monitoring\n#\n# CONFIG_DAMON is not set\n# end of Data Access Monitoring\n# end of Memory Management options\n\nCONFIG_NET=y\nCONFIG_NET_INGRESS=y\nCONFIG_NET_EGRESS=y\nCONFIG_NET_XGRESS=y\nCONFIG_SKB_EXTENSIONS=y\nCONFIG_NET_DEVMEM=y\nCONFIG_NET_SHAPER=y\nCONFIG_NET_CRC32C=y\n\n#\n# Networking options\n#\nCONFIG_PACKET=y\n# CONFIG_PACKET_DIAG is not set\n# CONFIG_INET_PSP is not set\nCONFIG_UNIX=y\nCONFIG_AF_UNIX_OOB=y\n# CONFIG_UNIX_DIAG is not set\n# CONFIG_TLS is not set\nCONFIG_XFRM=y\nCONFIG_XFRM_ALGO=y\nCONFIG_XFRM_USER=y\n# CONFIG_XFRM_INTERFACE is not set\n# CONFIG_XFRM_SUB_POLICY is not set\n# CONFIG_XFRM_MIGRATE is not set\n# CONFIG_XFRM_STATISTICS is not set\nCONFIG_XFRM_AH=y\nCONFIG_XFRM_ESP=y\n# CONFIG_NET_KEY is not set\n# CONFIG_XFRM_IPTFS is not set\n# CONFIG_DIBS is not set\nCONFIG_XDP_SOCKETS=y\n# CONFIG_XDP_SOCKETS_DIAG is not set\nCONFIG_NET_HANDSHAKE=y\nCONFIG_INET=y\nCONFIG_IP_MULTICAST=y\nCONFIG_IP_ADVANCED_ROUTER=y\n# CONFIG_IP_FIB_TRIE_STATS is not set\nCONFIG_IP_MULTIPLE_TABLES=y\nCONFIG_IP_ROUTE_MULTIPATH=y\nCONFIG_IP_ROUTE_VERBOSE=y\nCONFIG_IP_PNP=y\nCONFIG_IP_PNP_DHCP=y\nCONFIG_IP_PNP_BOOTP=y\nCONFIG_IP_PNP_RARP=y\nCONFIG_NET_IPIP=y\nCONFIG_NET_IPGRE_DEMUX=y\nCONFIG_NET_IP_TUNNEL=y\nCONFIG_NET_IPGRE=y\n# CONFIG_NET_IPGRE_BROADCAST is not set\nCONFIG_IP_MROUTE_COMMON=y\nCONFIG_IP_MROUTE=y\n# CONFIG_IP_MROUTE_MULTIPLE_TABLES is not set\nCONFIG_IP_PIMSM_V1=y\nCONFIG_IP_PIMSM_V2=y\nCONFIG_SYN_COOKIES=y\n# CONFIG_NET_IPVTI is not set\nCONFIG_NET_UDP_TUNNEL=y\nCONFIG_NET_FOU=y\nCONFIG_NET_FOU_IP_TUNNELS=y\n# CONFIG_INET_AH is not set\n# CONFIG_INET_ESP is not set\n# CONFIG_INET_IPCOMP is not set\nCONFIG_INET_TABLE_PERTURB_ORDER=16\nCONFIG_INET_TUNNEL=y\n# CONFIG_INET_DIAG is not set\nCONFIG_TCP_CONG_ADVANCED=y\n# CONFIG_TCP_CONG_BIC is not set\nCONFIG_TCP_CONG_CUBIC=y\n# CONFIG_TCP_CONG_WESTWOOD is not set\n# CONFIG_TCP_CONG_HTCP is not set\n# CONFIG_TCP_CONG_HSTCP is not set\n# CONFIG_TCP_CONG_HYBLA is not set\n# CONFIG_TCP_CONG_VEGAS is not set\n# CONFIG_TCP_CONG_NV is not set\n# CONFIG_TCP_CONG_SCALABLE is not set\n# CONFIG_TCP_CONG_LP is not set\n# CONFIG_TCP_CONG_VENO is not set\n# CONFIG_TCP_CONG_YEAH is not set\n# CONFIG_TCP_CONG_ILLINOIS is not set\n# CONFIG_TCP_CONG_DCTCP is not set\n# CONFIG_TCP_CONG_CDG is not set\n# CONFIG_TCP_CONG_BBR is not set\nCONFIG_DEFAULT_CUBIC=y\n# CONFIG_DEFAULT_RENO is not set\nCONFIG_DEFAULT_TCP_CONG=\"cubic\"\n# CONFIG_TCP_AO is not set\nCONFIG_TCP_MD5SIG=y\nCONFIG_IPV6=y\n# CONFIG_IPV6_ROUTER_PREF is not set\n# CONFIG_IPV6_OPTIMISTIC_DAD is not set\nCONFIG_INET6_AH=y\nCONFIG_INET6_ESP=y\n# CONFIG_INET6_ESP_OFFLOAD is not set\n# CONFIG_INET6_ESPINTCP is not set\n# CONFIG_INET6_IPCOMP is not set\n# CONFIG_IPV6_MIP6 is not set\n# CONFIG_IPV6_ILA is not set\nCONFIG_INET6_TUNNEL=y\n# CONFIG_IPV6_VTI is not set\nCONFIG_IPV6_SIT=y\n# CONFIG_IPV6_SIT_6RD is not set\nCONFIG_IPV6_NDISC_NODETYPE=y\nCONFIG_IPV6_TUNNEL=y\nCONFIG_IPV6_GRE=y\nCONFIG_IPV6_FOU=y\nCONFIG_IPV6_FOU_TUNNEL=y\n# CONFIG_IPV6_MULTIPLE_TABLES is not set\n# CONFIG_IPV6_MROUTE is not set\n# CONFIG_IPV6_SEG6_LWTUNNEL is not set\n# CONFIG_IPV6_SEG6_HMAC is not set\n# CONFIG_IPV6_RPL_LWTUNNEL is not set\n# CONFIG_IPV6_IOAM6_LWTUNNEL is not set\nCONFIG_NETLABEL=y\n# CONFIG_MPTCP is not set\nCONFIG_NETWORK_SECMARK=y\nCONFIG_NET_PTP_CLASSIFY=y\n# CONFIG_NETWORK_PHY_TIMESTAMPING is not set\nCONFIG_NETFILTER=y\nCONFIG_NETFILTER_ADVANCED=y\nCONFIG_BRIDGE_NETFILTER=y\n\n#\n# Core Netfilter Configuration\n#\nCONFIG_NETFILTER_INGRESS=y\nCONFIG_NETFILTER_EGRESS=y\nCONFIG_NETFILTER_SKIP_EGRESS=y\nCONFIG_NETFILTER_NETLINK=y\nCONFIG_NETFILTER_FAMILY_BRIDGE=y\nCONFIG_NETFILTER_BPF_LINK=y\n# CONFIG_NETFILTER_NETLINK_ACCT is not set\n# CONFIG_NETFILTER_NETLINK_QUEUE is not set\nCONFIG_NETFILTER_NETLINK_LOG=y\n# CONFIG_NETFILTER_NETLINK_OSF is not set\nCONFIG_NF_CONNTRACK=y\nCONFIG_NF_LOG_SYSLOG=y\n# CONFIG_NF_CONNTRACK_MARK is not set\nCONFIG_NF_CONNTRACK_SECMARK=y\n# CONFIG_NF_CONNTRACK_ZONES is not set\nCONFIG_NF_CONNTRACK_PROCFS=y\n# CONFIG_NF_CONNTRACK_EVENTS is not set\n# CONFIG_NF_CONNTRACK_TIMEOUT is not set\n# CONFIG_NF_CONNTRACK_TIMESTAMP is not set\n# CONFIG_NF_CONNTRACK_LABELS is not set\nCONFIG_NF_CT_PROTO_SCTP=y\nCONFIG_NF_CT_PROTO_UDPLITE=y\n# CONFIG_NF_CONNTRACK_AMANDA is not set\nCONFIG_NF_CONNTRACK_FTP=y\n# CONFIG_NF_CONNTRACK_H323 is not set\nCONFIG_NF_CONNTRACK_IRC=y\n# CONFIG_NF_CONNTRACK_NETBIOS_NS is not set\n# CONFIG_NF_CONNTRACK_SNMP is not set\n# CONFIG_NF_CONNTRACK_PPTP is not set\n# CONFIG_NF_CONNTRACK_SANE is not set\nCONFIG_NF_CONNTRACK_SIP=y\n# CONFIG_NF_CONNTRACK_TFTP is not set\nCONFIG_NF_CT_NETLINK=y\n# CONFIG_NETFILTER_NETLINK_GLUE_CT is not set\nCONFIG_NF_NAT=y\nCONFIG_NF_NAT_FTP=y\nCONFIG_NF_NAT_IRC=y\nCONFIG_NF_NAT_SIP=y\nCONFIG_NF_NAT_MASQUERADE=y\n# CONFIG_NF_TABLES is not set\nCONFIG_NETFILTER_XTABLES=y\n# CONFIG_NETFILTER_XTABLES_LEGACY is not set\n\n#\n# Xtables combined modules\n#\nCONFIG_NETFILTER_XT_MARK=y\n# CONFIG_NETFILTER_XT_CONNMARK is not set\n\n#\n# Xtables targets\n#\n# CONFIG_NETFILTER_XT_TARGET_AUDIT is not set\n# CONFIG_NETFILTER_XT_TARGET_CLASSIFY is not set\n# CONFIG_NETFILTER_XT_TARGET_CONNMARK is not set\nCONFIG_NETFILTER_XT_TARGET_CONNSECMARK=y\n# CONFIG_NETFILTER_XT_TARGET_HMARK is not set\n# CONFIG_NETFILTER_XT_TARGET_IDLETIMER is not set\nCONFIG_NETFILTER_XT_TARGET_LOG=y\n# CONFIG_NETFILTER_XT_TARGET_MARK is not set\nCONFIG_NETFILTER_XT_NAT=y\n# CONFIG_NETFILTER_XT_TARGET_NETMAP is not set\nCONFIG_NETFILTER_XT_TARGET_NFLOG=y\n# CONFIG_NETFILTER_XT_TARGET_NFQUEUE is not set\n# CONFIG_NETFILTER_XT_TARGET_RATEEST is not set\n# CONFIG_NETFILTER_XT_TARGET_REDIRECT is not set\nCONFIG_NETFILTER_XT_TARGET_MASQUERADE=y\n# CONFIG_NETFILTER_XT_TARGET_TEE is not set\nCONFIG_NETFILTER_XT_TARGET_SECMARK=y\nCONFIG_NETFILTER_XT_TARGET_TCPMSS=y\n\n#\n# Xtables matches\n#\nCONFIG_NETFILTER_XT_MATCH_ADDRTYPE=y\nCONFIG_NETFILTER_XT_MATCH_BPF=y\n# CONFIG_NETFILTER_XT_MATCH_CGROUP is not set\n# CONFIG_NETFILTER_XT_MATCH_CLUSTER is not set\nCONFIG_NETFILTER_XT_MATCH_COMMENT=y\n# CONFIG_NETFILTER_XT_MATCH_CONNBYTES is not set\n# CONFIG_NETFILTER_XT_MATCH_CONNLABEL is not set\n# CONFIG_NETFILTER_XT_MATCH_CONNLIMIT is not set\n# CONFIG_NETFILTER_XT_MATCH_CONNMARK is not set\nCONFIG_NETFILTER_XT_MATCH_CONNTRACK=y\n# CONFIG_NETFILTER_XT_MATCH_CPU is not set\n# CONFIG_NETFILTER_XT_MATCH_DCCP is not set\n# CONFIG_NETFILTER_XT_MATCH_DEVGROUP is not set\n# CONFIG_NETFILTER_XT_MATCH_DSCP is not set\n# CONFIG_NETFILTER_XT_MATCH_ECN is not set\n# CONFIG_NETFILTER_XT_MATCH_ESP is not set\n# CONFIG_NETFILTER_XT_MATCH_HASHLIMIT is not set\n# CONFIG_NETFILTER_XT_MATCH_HELPER is not set\n# CONFIG_NETFILTER_XT_MATCH_HL is not set\n# CONFIG_NETFILTER_XT_MATCH_IPCOMP is not set\n# CONFIG_NETFILTER_XT_MATCH_IPRANGE is not set\nCONFIG_NETFILTER_XT_MATCH_IPVS=y\n# CONFIG_NETFILTER_XT_MATCH_L2TP is not set\n# CONFIG_NETFILTER_XT_MATCH_LENGTH is not set\n# CONFIG_NETFILTER_XT_MATCH_LIMIT is not set\n# CONFIG_NETFILTER_XT_MATCH_MAC is not set\nCONFIG_NETFILTER_XT_MATCH_MARK=y\nCONFIG_NETFILTER_XT_MATCH_MULTIPORT=y\n# CONFIG_NETFILTER_XT_MATCH_NFACCT is not set\n# CONFIG_NETFILTER_XT_MATCH_OSF is not set\n# CONFIG_NETFILTER_XT_MATCH_OWNER is not set\nCONFIG_NETFILTER_XT_MATCH_POLICY=y\n# CONFIG_NETFILTER_XT_MATCH_PHYSDEV is not set\n# CONFIG_NETFILTER_XT_MATCH_PKTTYPE is not set\n# CONFIG_NETFILTER_XT_MATCH_QUOTA is not set\n# CONFIG_NETFILTER_XT_MATCH_RATEEST is not set\n# CONFIG_NETFILTER_XT_MATCH_REALM is not set\n# CONFIG_NETFILTER_XT_MATCH_RECENT is not set\n# CONFIG_NETFILTER_XT_MATCH_SCTP is not set\n# CONFIG_NETFILTER_XT_MATCH_SOCKET is not set\nCONFIG_NETFILTER_XT_MATCH_STATE=y\n# CONFIG_NETFILTER_XT_MATCH_STATISTIC is not set\n# CONFIG_NETFILTER_XT_MATCH_STRING is not set\n# CONFIG_NETFILTER_XT_MATCH_TCPMSS is not set\n# CONFIG_NETFILTER_XT_MATCH_TIME is not set\n# CONFIG_NETFILTER_XT_MATCH_U32 is not set\n# end of Core Netfilter Configuration\n\n# CONFIG_IP_SET is not set\nCONFIG_IP_VS=y\n# CONFIG_IP_VS_IPV6 is not set\n# CONFIG_IP_VS_DEBUG is not set\nCONFIG_IP_VS_TAB_BITS=12\n\n#\n# IPVS transport protocol load balancing support\n#\nCONFIG_IP_VS_PROTO_TCP=y\nCONFIG_IP_VS_PROTO_UDP=y\n# CONFIG_IP_VS_PROTO_ESP is not set\n# CONFIG_IP_VS_PROTO_AH is not set\n# CONFIG_IP_VS_PROTO_SCTP is not set\n\n#\n# IPVS scheduler\n#\nCONFIG_IP_VS_RR=y\n# CONFIG_IP_VS_WRR is not set\n# CONFIG_IP_VS_LC is not set\n# CONFIG_IP_VS_WLC is not set\n# CONFIG_IP_VS_FO is not set\n# CONFIG_IP_VS_OVF is not set\n# CONFIG_IP_VS_LBLC is not set\n# CONFIG_IP_VS_LBLCR is not set\n# CONFIG_IP_VS_DH is not set\n# CONFIG_IP_VS_SH is not set\n# CONFIG_IP_VS_MH is not set\n# CONFIG_IP_VS_SED is not set\n# CONFIG_IP_VS_NQ is not set\n# CONFIG_IP_VS_TWOS is not set\n\n#\n# IPVS SH scheduler\n#\nCONFIG_IP_VS_SH_TAB_BITS=8\n\n#\n# IPVS MH scheduler\n#\nCONFIG_IP_VS_MH_TAB_INDEX=12\n\n#\n# IPVS application helper\n#\n# CONFIG_IP_VS_FTP is not set\nCONFIG_IP_VS_NFCT=y\n# CONFIG_IP_VS_PE_SIP is not set\n\n#\n# IP: Netfilter Configuration\n#\nCONFIG_NF_DEFRAG_IPV4=y\n# CONFIG_NF_SOCKET_IPV4 is not set\n# CONFIG_NF_TPROXY_IPV4 is not set\n# CONFIG_NF_DUP_IPV4 is not set\nCONFIG_NF_LOG_ARP=y\nCONFIG_NF_LOG_IPV4=y\nCONFIG_NF_REJECT_IPV4=y\nCONFIG_IP_NF_IPTABLES=y\n# CONFIG_IP_NF_MATCH_AH is not set\n# CONFIG_IP_NF_MATCH_ECN is not set\n# CONFIG_IP_NF_MATCH_TTL is not set\n# CONFIG_IP_NF_TARGET_SYNPROXY is not set\n# end of IP: Netfilter Configuration\n\n#\n# IPv6: Netfilter Configuration\n#\n# CONFIG_NF_SOCKET_IPV6 is not set\n# CONFIG_NF_TPROXY_IPV6 is not set\n# CONFIG_NF_DUP_IPV6 is not set\nCONFIG_NF_REJECT_IPV6=y\nCONFIG_NF_LOG_IPV6=y\nCONFIG_IP6_NF_IPTABLES=y\n# CONFIG_IP6_NF_MATCH_AH is not set\n# CONFIG_IP6_NF_MATCH_EUI64 is not set\n# CONFIG_IP6_NF_MATCH_FRAG is not set\n# CONFIG_IP6_NF_MATCH_OPTS is not set\n# CONFIG_IP6_NF_MATCH_HL is not set\nCONFIG_IP6_NF_MATCH_IPV6HEADER=y\n# CONFIG_IP6_NF_MATCH_MH is not set\n# CONFIG_IP6_NF_MATCH_RT is not set\n# CONFIG_IP6_NF_MATCH_SRH is not set\n# CONFIG_IP6_NF_TARGET_SYNPROXY is not set\n# end of IPv6: Netfilter Configuration\n\nCONFIG_NF_DEFRAG_IPV6=y\n# CONFIG_NF_CONNTRACK_BRIDGE is not set\n# CONFIG_BRIDGE_NF_EBTABLES is not set\n# CONFIG_IP_SCTP is not set\n# CONFIG_RDS is not set\n# CONFIG_TIPC is not set\n# CONFIG_ATM is not set\n# CONFIG_L2TP is not set\nCONFIG_STP=y\nCONFIG_BRIDGE=y\nCONFIG_BRIDGE_IGMP_SNOOPING=y\n# CONFIG_BRIDGE_MRP is not set\n# CONFIG_BRIDGE_CFM is not set\n# CONFIG_NET_DSA is not set\n# CONFIG_VLAN_8021Q is not set\nCONFIG_LLC=y\n# CONFIG_LLC2 is not set\n# CONFIG_ATALK is not set\n# CONFIG_X25 is not set\n# CONFIG_LAPB is not set\n# CONFIG_PHONET is not set\n# CONFIG_6LOWPAN is not set\n# CONFIG_IEEE802154 is not set\nCONFIG_NET_SCHED=y\n\n#\n# Queueing/Scheduling\n#\n# CONFIG_NET_SCH_HTB is not set\n# CONFIG_NET_SCH_HFSC is not set\n# CONFIG_NET_SCH_PRIO is not set\n# CONFIG_NET_SCH_MULTIQ is not set\n# CONFIG_NET_SCH_RED is not set\n# CONFIG_NET_SCH_SFB is not set\n# CONFIG_NET_SCH_SFQ is not set\n# CONFIG_NET_SCH_TEQL is not set\n# CONFIG_NET_SCH_TBF is not set\n# CONFIG_NET_SCH_CBS is not set\n# CONFIG_NET_SCH_ETF is not set\n# CONFIG_NET_SCH_TAPRIO is not set\n# CONFIG_NET_SCH_GRED is not set\n# CONFIG_NET_SCH_NETEM is not set\n# CONFIG_NET_SCH_DRR is not set\n# CONFIG_NET_SCH_MQPRIO is not set\n# CONFIG_NET_SCH_SKBPRIO is not set\n# CONFIG_NET_SCH_CHOKE is not set\n# CONFIG_NET_SCH_QFQ is not set\n# CONFIG_NET_SCH_CODEL is not set\n# CONFIG_NET_SCH_FQ_CODEL is not set\n# CONFIG_NET_SCH_CAKE is not set\n# CONFIG_NET_SCH_FQ is not set\n# CONFIG_NET_SCH_HHF is not set\n# CONFIG_NET_SCH_PIE is not set\nCONFIG_NET_SCH_INGRESS=y\n# CONFIG_NET_SCH_PLUG is not set\n# CONFIG_NET_SCH_ETS is not set\nCONFIG_NET_SCH_BPF=y\n# CONFIG_NET_SCH_DUALPI2 is not set\n# CONFIG_NET_SCH_DEFAULT is not set\n\n#\n# Classification\n#\nCONFIG_NET_CLS=y\n# CONFIG_NET_CLS_BASIC is not set\n# CONFIG_NET_CLS_ROUTE4 is not set\n# CONFIG_NET_CLS_FW is not set\n# CONFIG_NET_CLS_U32 is not set\n# CONFIG_NET_CLS_FLOW is not set\nCONFIG_NET_CLS_CGROUP=y\nCONFIG_NET_CLS_BPF=y\nCONFIG_NET_CLS_FLOWER=y\n# CONFIG_NET_CLS_MATCHALL is not set\nCONFIG_NET_EMATCH=y\nCONFIG_NET_EMATCH_STACK=32\n# CONFIG_NET_EMATCH_CMP is not set\n# CONFIG_NET_EMATCH_NBYTE is not set\n# CONFIG_NET_EMATCH_U32 is not set\n# CONFIG_NET_EMATCH_META is not set\n# CONFIG_NET_EMATCH_TEXT is not set\n# CONFIG_NET_EMATCH_IPT is not set\nCONFIG_NET_CLS_ACT=y\n# CONFIG_NET_ACT_POLICE is not set\n# CONFIG_NET_ACT_GACT is not set\n# CONFIG_NET_ACT_MIRRED is not set\n# CONFIG_NET_ACT_SAMPLE is not set\n# CONFIG_NET_ACT_NAT is not set\n# CONFIG_NET_ACT_PEDIT is not set\n# CONFIG_NET_ACT_SIMP is not set\n# CONFIG_NET_ACT_SKBEDIT is not set\n# CONFIG_NET_ACT_CSUM is not set\n# CONFIG_NET_ACT_MPLS is not set\n# CONFIG_NET_ACT_VLAN is not set\n# CONFIG_NET_ACT_BPF is not set\n# CONFIG_NET_ACT_SKBMOD is not set\n# CONFIG_NET_ACT_IFE is not set\n# CONFIG_NET_ACT_TUNNEL_KEY is not set\n# CONFIG_NET_ACT_GATE is not set\n# CONFIG_NET_TC_SKB_EXT is not set\nCONFIG_NET_SCH_FIFO=y\n# CONFIG_DCB is not set\nCONFIG_DNS_RESOLVER=y\n# CONFIG_BATMAN_ADV is not set\n# CONFIG_OPENVSWITCH is not set\n# CONFIG_VSOCKETS is not set\n# CONFIG_NETLINK_DIAG is not set\nCONFIG_MPLS=y\nCONFIG_NET_MPLS_GSO=y\nCONFIG_MPLS_ROUTING=y\nCONFIG_MPLS_IPTUNNEL=y\n# CONFIG_NET_NSH is not set\n# CONFIG_HSR is not set\n# CONFIG_NET_SWITCHDEV is not set\nCONFIG_NET_L3_MASTER_DEV=y\n# CONFIG_QRTR is not set\n# CONFIG_NET_NCSI is not set\nCONFIG_PCPU_DEV_REFCNT=y\nCONFIG_MAX_SKB_FRAGS=17\nCONFIG_RPS=y\nCONFIG_RFS_ACCEL=y\nCONFIG_SOCK_RX_QUEUE_MAPPING=y\nCONFIG_XPS=y\nCONFIG_CGROUP_NET_PRIO=y\nCONFIG_CGROUP_NET_CLASSID=y\nCONFIG_NET_RX_BUSY_POLL=y\nCONFIG_BQL=y\nCONFIG_BPF_STREAM_PARSER=y\nCONFIG_NET_FLOW_LIMIT=y\n\n#\n# Network testing\n#\n# CONFIG_NET_PKTGEN is not set\n# CONFIG_NET_DROP_MONITOR is not set\n# end of Network testing\n# end of Networking options\n\n# CONFIG_HAMRADIO is not set\n# CONFIG_CAN is not set\n# CONFIG_BT is not set\n# CONFIG_AF_RXRPC is not set\n# CONFIG_AF_KCM is not set\nCONFIG_STREAM_PARSER=y\n# CONFIG_MCTP is not set\nCONFIG_FIB_RULES=y\nCONFIG_WIRELESS=y\nCONFIG_CFG80211=y\n# CONFIG_NL80211_TESTMODE is not set\n# CONFIG_CFG80211_DEVELOPER_WARNINGS is not set\n# CONFIG_CFG80211_CERTIFICATION_ONUS is not set\nCONFIG_CFG80211_REQUIRE_SIGNED_REGDB=y\nCONFIG_CFG80211_USE_KERNEL_REGDB_KEYS=y\nCONFIG_CFG80211_DEFAULT_PS=y\n# CONFIG_CFG80211_DEBUGFS is not set\nCONFIG_CFG80211_CRDA_SUPPORT=y\n# CONFIG_CFG80211_WEXT is not set\nCONFIG_MAC80211=y\nCONFIG_MAC80211_HAS_RC=y\nCONFIG_MAC80211_RC_MINSTREL=y\nCONFIG_MAC80211_RC_DEFAULT_MINSTREL=y\nCONFIG_MAC80211_RC_DEFAULT=\"minstrel_ht\"\n# CONFIG_MAC80211_MESH is not set\n# CONFIG_MAC80211_MESSAGE_TRACING is not set\n# CONFIG_MAC80211_DEBUG_MENU is not set\nCONFIG_MAC80211_STA_HASH_MAX_SIZE=0\nCONFIG_RFKILL=y\n# CONFIG_RFKILL_INPUT is not set\nCONFIG_NET_9P=y\nCONFIG_NET_9P_FD=y\nCONFIG_NET_9P_VIRTIO=y\n# CONFIG_NET_9P_DEBUG is not set\n# CONFIG_CAIF is not set\n# CONFIG_CEPH_LIB is not set\n# CONFIG_NFC is not set\n# CONFIG_PSAMPLE is not set\n# CONFIG_NET_IFE is not set\nCONFIG_LWTUNNEL=y\nCONFIG_LWTUNNEL_BPF=y\nCONFIG_DST_CACHE=y\nCONFIG_GRO_CELLS=y\nCONFIG_NET_SELFTESTS=y\nCONFIG_NET_SOCK_MSG=y\nCONFIG_NET_DEVLINK=y\nCONFIG_PAGE_POOL=y\n# CONFIG_PAGE_POOL_STATS is not set\nCONFIG_FAILOVER=y\nCONFIG_ETHTOOL_NETLINK=y\n\n#\n# Device Drivers\n#\nCONFIG_HAVE_PCI=y\nCONFIG_GENERIC_PCI_IOMAP=y\nCONFIG_PCI=y\nCONFIG_PCI_DOMAINS=y\nCONFIG_PCIEPORTBUS=y\n# CONFIG_HOTPLUG_PCI_PCIE is not set\n# CONFIG_PCIEAER is not set\nCONFIG_PCIEASPM=y\nCONFIG_PCIEASPM_DEFAULT=y\n# CONFIG_PCIEASPM_POWERSAVE is not set\n# CONFIG_PCIEASPM_POWER_SUPERSAVE is not set\n# CONFIG_PCIEASPM_PERFORMANCE is not set\nCONFIG_PCIE_PME=y\n# CONFIG_PCIE_PTM is not set\nCONFIG_PCI_MSI=y\nCONFIG_PCI_QUIRKS=y\n# CONFIG_PCI_DEBUG is not set\n# CONFIG_PCI_STUB is not set\nCONFIG_PCI_ATS=y\n# CONFIG_PCI_TSM is not set\n# CONFIG_PCI_DOE is not set\nCONFIG_PCI_LOCKLESS_CONFIG=y\n# CONFIG_PCI_IOV is not set\nCONFIG_PCI_PRI=y\nCONFIG_PCI_PASID=y\n# CONFIG_PCIE_TPH is not set\nCONFIG_PCI_LABEL=y\n# CONFIG_PCIE_BUS_TUNE_OFF is not set\nCONFIG_PCIE_BUS_DEFAULT=y\n# CONFIG_PCIE_BUS_SAFE is not set\n# CONFIG_PCIE_BUS_PERFORMANCE is not set\n# CONFIG_PCIE_BUS_PEER2PEER is not set\nCONFIG_VGA_ARB=y\nCONFIG_VGA_ARB_MAX_GPUS=16\nCONFIG_HOTPLUG_PCI=y\n# CONFIG_HOTPLUG_PCI_ACPI is not set\n# CONFIG_HOTPLUG_PCI_CPCI is not set\n# CONFIG_HOTPLUG_PCI_OCTEONEP is not set\n# CONFIG_HOTPLUG_PCI_SHPC is not set\n\n#\n# PCI controller drivers\n#\n# CONFIG_VMD is not set\n\n#\n# Cadence-based PCIe controllers\n#\n# end of Cadence-based PCIe controllers\n\n#\n# DesignWare-based PCIe controllers\n#\n# CONFIG_PCI_MESON is not set\n# CONFIG_PCIE_DW_PLAT_HOST is not set\n# end of DesignWare-based PCIe controllers\n\n#\n# Mobiveil-based PCIe controllers\n#\n# end of Mobiveil-based PCIe controllers\n\n#\n# PLDA-based PCIe controllers\n#\n# end of PLDA-based PCIe controllers\n# end of PCI controller drivers\n\n#\n# PCI Endpoint\n#\n# CONFIG_PCI_ENDPOINT is not set\n# end of PCI Endpoint\n\n#\n# PCI switch controller drivers\n#\n# CONFIG_PCI_SW_SWITCHTEC is not set\n# end of PCI switch controller drivers\n\n# CONFIG_PCI_PWRCTRL_SLOT is not set\n# CONFIG_PCI_PWRCTRL_TC9563 is not set\n# CONFIG_CXL_BUS is not set\nCONFIG_PCCARD=y\nCONFIG_PCMCIA=y\nCONFIG_PCMCIA_LOAD_CIS=y\nCONFIG_CARDBUS=y\n\n#\n# PC-card bridges\n#\nCONFIG_YENTA=y\nCONFIG_YENTA_O2=y\nCONFIG_YENTA_RICOH=y\nCONFIG_YENTA_TI=y\nCONFIG_YENTA_ENE_TUNE=y\nCONFIG_YENTA_TOSHIBA=y\n# CONFIG_PD6729 is not set\n# CONFIG_I82092 is not set\nCONFIG_PCCARD_NONSTATIC=y\n# CONFIG_RAPIDIO is not set\n# CONFIG_PC104 is not set\n\n#\n# Generic Driver Options\n#\n# CONFIG_UEVENT_HELPER is not set\nCONFIG_DEVTMPFS=y\nCONFIG_DEVTMPFS_MOUNT=y\n# CONFIG_DEVTMPFS_SAFE is not set\nCONFIG_STANDALONE=y\nCONFIG_PREVENT_FIRMWARE_BUILD=y\n\n#\n# Firmware loader\n#\nCONFIG_FW_LOADER=y\nCONFIG_EXTRA_FIRMWARE=\"\"\n# CONFIG_FW_LOADER_USER_HELPER is not set\n# CONFIG_FW_LOADER_COMPRESS is not set\nCONFIG_FW_CACHE=y\n# CONFIG_FW_UPLOAD is not set\n# end of Firmware loader\n\nCONFIG_ALLOW_DEV_COREDUMP=y\n# CONFIG_DEBUG_DRIVER is not set\nCONFIG_DEBUG_DEVRES=y\n# CONFIG_DEBUG_TEST_DRIVER_REMOVE is not set\n# CONFIG_TEST_ASYNC_DRIVER_PROBE is not set\nCONFIG_GENERIC_CPU_DEVICES=y\nCONFIG_GENERIC_CPU_AUTOPROBE=y\nCONFIG_GENERIC_CPU_VULNERABILITIES=y\nCONFIG_DMA_SHARED_BUFFER=y\n# CONFIG_DMA_FENCE_TRACE is not set\n# CONFIG_FW_DEVLINK_SYNC_STATE_TIMEOUT is not set\n# end of Generic Driver Options\n\n#\n# Bus devices\n#\n# CONFIG_MHI_BUS is not set\n# CONFIG_MHI_BUS_EP is not set\n# end of Bus devices\n\nCONFIG_CONNECTOR=y\nCONFIG_PROC_EVENTS=y\n\n#\n# Firmware Drivers\n#\n\n#\n# ARM System Control and Management Interface Protocol\n#\n# end of ARM System Control and Management Interface Protocol\n\n# CONFIG_EDD is not set\nCONFIG_FIRMWARE_MEMMAP=y\nCONFIG_DMIID=y\n# CONFIG_DMI_SYSFS is not set\nCONFIG_DMI_SCAN_MACHINE_NON_EFI_FALLBACK=y\n# CONFIG_FW_CFG_SYSFS is not set\nCONFIG_SYSFB=y\n# CONFIG_SYSFB_SIMPLEFB is not set\n# CONFIG_GOOGLE_FIRMWARE is not set\n\n#\n# EFI (Extensible Firmware Interface) Support\n#\nCONFIG_EFI_ESRT=y\nCONFIG_EFI_RUNTIME_WRAPPERS=y\n# CONFIG_EFI_BOOTLOADER_CONTROL is not set\n# CONFIG_EFI_CAPSULE_LOADER is not set\n# CONFIG_EFI_TEST is not set\n# CONFIG_EFI_RCI2_TABLE is not set\n# CONFIG_EFI_DISABLE_PCI_DMA is not set\nCONFIG_EFI_EARLYCON=y\nCONFIG_EFI_CUSTOM_SSDT_OVERLAYS=y\n# CONFIG_EFI_DISABLE_RUNTIME is not set\n# CONFIG_EFI_COCO_SECRET is not set\n# CONFIG_OVMF_DEBUG_LOG is not set\n# end of EFI (Extensible Firmware Interface) Support\n\n#\n# Qualcomm firmware drivers\n#\n# end of Qualcomm firmware drivers\n\n#\n# Tegra firmware driver\n#\n# end of Tegra firmware driver\n# end of Firmware Drivers\n\n# CONFIG_FWCTL is not set\n# CONFIG_GNSS is not set\n# CONFIG_MTD is not set\n# CONFIG_OF is not set\nCONFIG_ARCH_MIGHT_HAVE_PC_PARPORT=y\n# CONFIG_PARPORT is not set\nCONFIG_PNP=y\nCONFIG_PNP_DEBUG_MESSAGES=y\n\n#\n# Protocols\n#\nCONFIG_PNPACPI=y\nCONFIG_BLK_DEV=y\n# CONFIG_BLK_DEV_NULL_BLK is not set\n# CONFIG_BLK_DEV_FD is not set\nCONFIG_CDROM=y\n# CONFIG_BLK_DEV_PCIESSD_MTIP32XX is not set\n# CONFIG_ZRAM is not set\nCONFIG_BLK_DEV_LOOP=y\nCONFIG_BLK_DEV_LOOP_MIN_COUNT=8\n# CONFIG_BLK_DEV_DRBD is not set\n# CONFIG_BLK_DEV_NBD is not set\n# CONFIG_BLK_DEV_RAM is not set\n# CONFIG_ATA_OVER_ETH is not set\n# CONFIG_VIRTIO_BLK is not set\n# CONFIG_BLK_DEV_RBD is not set\n# CONFIG_BLK_DEV_UBLK is not set\n\n#\n# NVME Support\n#\nCONFIG_NVME_CORE=y\nCONFIG_BLK_DEV_NVME=y\n# CONFIG_NVME_MULTIPATH is not set\n# CONFIG_NVME_VERBOSE_ERRORS is not set\n# CONFIG_NVME_HWMON is not set\n# CONFIG_NVME_FC is not set\n# CONFIG_NVME_TCP is not set\n# CONFIG_NVME_HOST_AUTH is not set\n# CONFIG_NVME_TARGET is not set\n# end of NVME Support\n\n#\n# Misc devices\n#\n# CONFIG_AD525X_DPOT is not set\n# CONFIG_DUMMY_IRQ is not set\n# CONFIG_IBM_ASM is not set\n# CONFIG_PHANTOM is not set\n# CONFIG_RPMB is not set\n# CONFIG_TI_FPC202 is not set\n# CONFIG_TIFM_CORE is not set\n# CONFIG_ICS932S401 is not set\n# CONFIG_ENCLOSURE_SERVICES is not set\n# CONFIG_HP_ILO is not set\n# CONFIG_APDS9802ALS is not set\n# CONFIG_ISL29003 is not set\n# CONFIG_ISL29020 is not set\n# CONFIG_SENSORS_TSL2550 is not set\n# CONFIG_SENSORS_BH1770 is not set\n# CONFIG_SENSORS_APDS990X is not set\n# CONFIG_HMC6352 is not set\n# CONFIG_DS1682 is not set\n# CONFIG_SRAM is not set\n# CONFIG_DW_XDATA_PCIE is not set\n# CONFIG_PCI_ENDPOINT_TEST is not set\n# CONFIG_XILINX_SDFEC is not set\n# CONFIG_NTSYNC is not set\n# CONFIG_NSM is not set\n# CONFIG_C2PORT is not set\n\n#\n# EEPROM support\n#\n# CONFIG_EEPROM_AT24 is not set\n# CONFIG_EEPROM_MAX6875 is not set\nCONFIG_EEPROM_93CX6=y\n# CONFIG_EEPROM_IDT_89HPESX is not set\n# CONFIG_EEPROM_EE1004 is not set\n# CONFIG_EEPROM_M24LR is not set\n# end of EEPROM support\n\n# CONFIG_CB710_CORE is not set\n# CONFIG_SENSORS_LIS3_I2C is not set\n# CONFIG_ALTERA_STAPL is not set\n# CONFIG_INTEL_MEI is not set\n# CONFIG_VMWARE_VMCI is not set\n# CONFIG_GENWQE is not set\n# CONFIG_BCM_VK is not set\n# CONFIG_MISC_ALCOR_PCI is not set\n# CONFIG_MISC_RTSX_PCI is not set\n# CONFIG_MISC_RTSX_USB is not set\n# CONFIG_UACCE is not set\n# CONFIG_PVPANIC is not set\n# CONFIG_KEBA_CP500 is not set\n# end of Misc devices\n\n#\n# SCSI device support\n#\nCONFIG_SCSI_MOD=y\n# CONFIG_RAID_ATTRS is not set\nCONFIG_SCSI_COMMON=y\nCONFIG_SCSI=y\nCONFIG_SCSI_DMA=y\nCONFIG_SCSI_PROC_FS=y\n\n#\n# SCSI support type (disk, tape, CD-ROM)\n#\nCONFIG_BLK_DEV_SD=y\n# CONFIG_CHR_DEV_ST is not set\nCONFIG_BLK_DEV_SR=y\nCONFIG_CHR_DEV_SG=y\nCONFIG_BLK_DEV_BSG=y\n# CONFIG_CHR_DEV_SCH is not set\nCONFIG_SCSI_CONSTANTS=y\n# CONFIG_SCSI_LOGGING is not set\n# CONFIG_SCSI_SCAN_ASYNC is not set\n\n#\n# SCSI Transports\n#\nCONFIG_SCSI_SPI_ATTRS=y\n# CONFIG_SCSI_FC_ATTRS is not set\n# CONFIG_SCSI_ISCSI_ATTRS is not set\n# CONFIG_SCSI_SAS_ATTRS is not set\n# CONFIG_SCSI_SAS_LIBSAS is not set\n# CONFIG_SCSI_SRP_ATTRS is not set\n# end of SCSI Transports\n\n# CONFIG_SCSI_LOWLEVEL is not set\n# CONFIG_SCSI_DH is not set\n# end of SCSI device support\n\nCONFIG_ATA=y\nCONFIG_SATA_HOST=y\nCONFIG_PATA_TIMINGS=y\nCONFIG_ATA_VERBOSE_ERROR=y\nCONFIG_ATA_FORCE=y\nCONFIG_ATA_ACPI=y\n# CONFIG_SATA_ZPODD is not set\nCONFIG_SATA_PMP=y\n\n#\n# Controllers with non-SFF native interface\n#\nCONFIG_SATA_AHCI=y\nCONFIG_SATA_MOBILE_LPM_POLICY=0\n# CONFIG_SATA_AHCI_PLATFORM is not set\n# CONFIG_AHCI_DWC is not set\n# CONFIG_SATA_INIC162X is not set\n# CONFIG_SATA_ACARD_AHCI is not set\n# CONFIG_SATA_SIL24 is not set\nCONFIG_ATA_SFF=y\n\n#\n# SFF controllers with custom DMA interface\n#\n# CONFIG_PDC_ADMA is not set\n# CONFIG_SATA_QSTOR is not set\n# CONFIG_SATA_SX4 is not set\nCONFIG_ATA_BMDMA=y\n\n#\n# SATA SFF controllers with BMDMA\n#\nCONFIG_ATA_PIIX=y\n# CONFIG_SATA_DWC is not set\n# CONFIG_SATA_MV is not set\n# CONFIG_SATA_NV is not set\n# CONFIG_SATA_PROMISE is not set\n# CONFIG_SATA_SIL is not set\n# CONFIG_SATA_SIS is not set\n# CONFIG_SATA_SVW is not set\n# CONFIG_SATA_ULI is not set\n# CONFIG_SATA_VIA is not set\n# CONFIG_SATA_VITESSE is not set\n\n#\n# PATA SFF controllers with BMDMA\n#\n# CONFIG_PATA_ALI is not set\nCONFIG_PATA_AMD=y\n# CONFIG_PATA_ARTOP is not set\n# CONFIG_PATA_ATIIXP is not set\n# CONFIG_PATA_ATP867X is not set\n# CONFIG_PATA_CMD64X is not set\n# CONFIG_PATA_CYPRESS is not set\n# CONFIG_PATA_EFAR is not set\n# CONFIG_PATA_HPT366 is not set\n# CONFIG_PATA_HPT37X is not set\n# CONFIG_PATA_HPT3X2N is not set\n# CONFIG_PATA_HPT3X3 is not set\n# CONFIG_PATA_IT8213 is not set\n# CONFIG_PATA_IT821X is not set\n# CONFIG_PATA_JMICRON is not set\n# CONFIG_PATA_MARVELL is not set\n# CONFIG_PATA_NETCELL is not set\n# CONFIG_PATA_NINJA32 is not set\n# CONFIG_PATA_NS87415 is not set\nCONFIG_PATA_OLDPIIX=y\n# CONFIG_PATA_OPTIDMA is not set\n# CONFIG_PATA_PDC2027X is not set\n# CONFIG_PATA_PDC_OLD is not set\n# CONFIG_PATA_RADISYS is not set\n# CONFIG_PATA_RDC is not set\nCONFIG_PATA_SCH=y\n# CONFIG_PATA_SERVERWORKS is not set\n# CONFIG_PATA_SIL680 is not set\n# CONFIG_PATA_SIS is not set\n# CONFIG_PATA_TOSHIBA is not set\n# CONFIG_PATA_TRIFLEX is not set\n# CONFIG_PATA_VIA is not set\n# CONFIG_PATA_WINBOND is not set\n\n#\n# PIO-only SFF controllers\n#\n# CONFIG_PATA_CMD640_PCI is not set\n# CONFIG_PATA_MPIIX is not set\n# CONFIG_PATA_NS87410 is not set\n# CONFIG_PATA_OPTI is not set\n# CONFIG_PATA_PCMCIA is not set\n# CONFIG_PATA_RZ1000 is not set\n\n#\n# Generic fallback / legacy drivers\n#\n# CONFIG_PATA_ACPI is not set\n# CONFIG_ATA_GENERIC is not set\n# CONFIG_PATA_LEGACY is not set\nCONFIG_MD=y\nCONFIG_BLK_DEV_MD=y\nCONFIG_MD_BITMAP=y\n# CONFIG_MD_LLBITMAP is not set\nCONFIG_MD_AUTODETECT=y\n# CONFIG_MD_BITMAP_FILE is not set\n# CONFIG_MD_LINEAR is not set\n# CONFIG_MD_RAID0 is not set\n# CONFIG_MD_RAID1 is not set\n# CONFIG_MD_RAID10 is not set\n# CONFIG_MD_RAID456 is not set\n# CONFIG_BCACHE is not set\nCONFIG_BLK_DEV_DM_BUILTIN=y\nCONFIG_BLK_DEV_DM=y\n# CONFIG_DM_DEBUG is not set\n# CONFIG_DM_UNSTRIPED is not set\n# CONFIG_DM_CRYPT is not set\n# CONFIG_DM_SNAPSHOT is not set\n# CONFIG_DM_THIN_PROVISIONING is not set\n# CONFIG_DM_CACHE is not set\n# CONFIG_DM_WRITECACHE is not set\n# CONFIG_DM_EBS is not set\n# CONFIG_DM_ERA is not set\n# CONFIG_DM_CLONE is not set\nCONFIG_DM_MIRROR=y\n# CONFIG_DM_LOG_USERSPACE is not set\n# CONFIG_DM_RAID is not set\nCONFIG_DM_ZERO=y\n# CONFIG_DM_MULTIPATH is not set\n# CONFIG_DM_DELAY is not set\n# CONFIG_DM_DUST is not set\n# CONFIG_DM_INIT is not set\n# CONFIG_DM_UEVENT is not set\n# CONFIG_DM_FLAKEY is not set\n# CONFIG_DM_VERITY is not set\n# CONFIG_DM_SWITCH is not set\n# CONFIG_DM_LOG_WRITES is not set\n# CONFIG_DM_INTEGRITY is not set\n# CONFIG_DM_AUDIT is not set\n# CONFIG_DM_VDO is not set\n# CONFIG_TARGET_CORE is not set\n# CONFIG_FUSION is not set\n\n#\n# IEEE 1394 (FireWire) support\n#\n# CONFIG_FIREWIRE is not set\n# CONFIG_FIREWIRE_NOSY is not set\n# end of IEEE 1394 (FireWire) support\n\n# CONFIG_MACINTOSH_DRIVERS is not set\nCONFIG_NETDEVICES=y\nCONFIG_MII=y\nCONFIG_NET_CORE=y\n# CONFIG_BONDING is not set\nCONFIG_DUMMY=y\n# CONFIG_WIREGUARD is not set\n# CONFIG_OVPN is not set\n# CONFIG_EQUALIZER is not set\n# CONFIG_NET_FC is not set\n# CONFIG_NET_TEAM is not set\nCONFIG_MACVLAN=y\n# CONFIG_MACVTAP is not set\nCONFIG_IPVLAN_L3S=y\nCONFIG_IPVLAN=y\n# CONFIG_IPVTAP is not set\nCONFIG_VXLAN=y\nCONFIG_GENEVE=y\n# CONFIG_BAREUDP is not set\n# CONFIG_GTP is not set\n# CONFIG_PFCP is not set\n# CONFIG_AMT is not set\n# CONFIG_MACSEC is not set\nCONFIG_NETCONSOLE=y\n# CONFIG_NETCONSOLE_DYNAMIC is not set\n# CONFIG_NETCONSOLE_EXTENDED_LOG is not set\nCONFIG_NETPOLL=y\nCONFIG_NET_POLL_CONTROLLER=y\nCONFIG_TUN=y\n# CONFIG_TUN_VNET_CROSS_LE is not set\nCONFIG_VETH=y\nCONFIG_VIRTIO_NET=y\n# CONFIG_NLMON is not set\nCONFIG_NETKIT=y\n# CONFIG_ARCNET is not set\nCONFIG_ETHERNET=y\nCONFIG_NET_VENDOR_3COM=y\n# CONFIG_PCMCIA_3C574 is not set\n# CONFIG_PCMCIA_3C589 is not set\n# CONFIG_VORTEX is not set\n# CONFIG_TYPHOON is not set\nCONFIG_NET_VENDOR_ADAPTEC=y\n# CONFIG_ADAPTEC_STARFIRE is not set\nCONFIG_NET_VENDOR_AGERE=y\n# CONFIG_ET131X is not set\nCONFIG_NET_VENDOR_ALACRITECH=y\n# CONFIG_SLICOSS is not set\nCONFIG_NET_VENDOR_ALTEON=y\n# CONFIG_ACENIC is not set\n# CONFIG_ALTERA_TSE is not set\nCONFIG_NET_VENDOR_AMAZON=y\n# CONFIG_ENA_ETHERNET is not set\nCONFIG_NET_VENDOR_AMD=y\n# CONFIG_AMD8111_ETH is not set\n# CONFIG_PCNET32 is not set\n# CONFIG_PCMCIA_NMCLAN is not set\n# CONFIG_AMD_XGBE is not set\n# CONFIG_PDS_CORE is not set\nCONFIG_NET_VENDOR_AQUANTIA=y\n# CONFIG_AQTION is not set\nCONFIG_NET_VENDOR_ARC=y\n# CONFIG_NET_VENDOR_ASIX is not set\nCONFIG_NET_VENDOR_ATHEROS=y\n# CONFIG_ATL2 is not set\n# CONFIG_ATL1 is not set\n# CONFIG_ATL1E is not set\n# CONFIG_ATL1C is not set\n# CONFIG_ALX is not set\n# CONFIG_CX_ECAT is not set\nCONFIG_NET_VENDOR_BROADCOM=y\n# CONFIG_B44 is not set\n# CONFIG_BCMGENET is not set\n# CONFIG_BNX2 is not set\n# CONFIG_CNIC is not set\nCONFIG_TIGON3=y\nCONFIG_TIGON3_HWMON=y\n# CONFIG_BNX2X is not set\n# CONFIG_SYSTEMPORT is not set\n# CONFIG_BNXT is not set\n# CONFIG_BNGE is not set\nCONFIG_NET_VENDOR_CADENCE=y\n# CONFIG_MACB is not set\nCONFIG_NET_VENDOR_CAVIUM=y\n# CONFIG_THUNDER_NIC_PF is not set\n# CONFIG_THUNDER_NIC_VF is not set\n# CONFIG_THUNDER_NIC_BGX is not set\n# CONFIG_THUNDER_NIC_RGX is not set\n# CONFIG_CAVIUM_PTP is not set\n# CONFIG_LIQUIDIO is not set\n# CONFIG_LIQUIDIO_VF is not set\nCONFIG_NET_VENDOR_CHELSIO=y\n# CONFIG_CHELSIO_T1 is not set\n# CONFIG_CHELSIO_T3 is not set\n# CONFIG_CHELSIO_T4 is not set\n# CONFIG_CHELSIO_T4VF is not set\nCONFIG_NET_VENDOR_CISCO=y\n# CONFIG_ENIC is not set\nCONFIG_NET_VENDOR_CORTINA=y\n# CONFIG_NET_VENDOR_DAVICOM is not set\n# CONFIG_DNET is not set\nCONFIG_NET_VENDOR_DEC=y\nCONFIG_NET_TULIP=y\n# CONFIG_DE2104X is not set\n# CONFIG_TULIP is not set\n# CONFIG_WINBOND_840 is not set\n# CONFIG_DM9102 is not set\n# CONFIG_ULI526X is not set\n# CONFIG_PCMCIA_XIRCOM is not set\nCONFIG_NET_VENDOR_DLINK=y\n# CONFIG_DL2K is not set\n# CONFIG_SUNDANCE is not set\nCONFIG_NET_VENDOR_EMULEX=y\n# CONFIG_BE2NET is not set\n# CONFIG_NET_VENDOR_ENGLEDER is not set\nCONFIG_NET_VENDOR_EZCHIP=y\nCONFIG_NET_VENDOR_FUJITSU=y\n# CONFIG_PCMCIA_FMVJ18X is not set\n# CONFIG_NET_VENDOR_FUNGIBLE is not set\nCONFIG_NET_VENDOR_GOOGLE=y\n# CONFIG_GVE is not set\nCONFIG_NET_VENDOR_HISILICON=y\n# CONFIG_HIBMCGE is not set\nCONFIG_NET_VENDOR_HUAWEI=y\n# CONFIG_HINIC is not set\n# CONFIG_HINIC3 is not set\nCONFIG_NET_VENDOR_I825XX=y\nCONFIG_NET_VENDOR_INTEL=y\nCONFIG_E100=y\nCONFIG_E1000=y\nCONFIG_E1000E=y\nCONFIG_E1000E_HWTS=y\n# CONFIG_IGB is not set\n# CONFIG_IGBVF is not set\n# CONFIG_IXGBE is not set\n# CONFIG_IXGBEVF is not set\n# CONFIG_I40E is not set\n# CONFIG_I40EVF is not set\n# CONFIG_ICE is not set\n# CONFIG_FM10K is not set\n# CONFIG_IGC is not set\n# CONFIG_IDPF is not set\n# CONFIG_JME is not set\nCONFIG_NET_VENDOR_LITEX=y\nCONFIG_NET_VENDOR_MARVELL=y\n# CONFIG_MVMDIO is not set\n# CONFIG_SKGE is not set\nCONFIG_SKY2=y\n# CONFIG_SKY2_DEBUG is not set\n# CONFIG_OCTEON_EP is not set\n# CONFIG_OCTEON_EP_VF is not set\nCONFIG_NET_VENDOR_MELLANOX=y\n# CONFIG_MLX4_EN is not set\n# CONFIG_MLX5_CORE is not set\n# CONFIG_MLXSW_CORE is not set\n# CONFIG_MLXFW is not set\n# CONFIG_NET_VENDOR_META is not set\nCONFIG_NET_VENDOR_MICREL=y\n# CONFIG_KS8842 is not set\n# CONFIG_KS8851_MLL is not set\n# CONFIG_KSZ884X_PCI is not set\nCONFIG_NET_VENDOR_MICROCHIP=y\n# CONFIG_LAN743X is not set\n# CONFIG_VCAP is not set\nCONFIG_NET_VENDOR_MICROSEMI=y\nCONFIG_NET_VENDOR_MICROSOFT=y\n# CONFIG_NET_VENDOR_MUCSE is not set\nCONFIG_NET_VENDOR_MYRI=y\n# CONFIG_MYRI10GE is not set\n# CONFIG_FEALNX is not set\nCONFIG_NET_VENDOR_NI=y\n# CONFIG_NI_XGE_MANAGEMENT_ENET is not set\nCONFIG_NET_VENDOR_NATSEMI=y\n# CONFIG_NATSEMI is not set\n# CONFIG_NS83820 is not set\nCONFIG_NET_VENDOR_NETERION=y\n# CONFIG_S2IO is not set\nCONFIG_NET_VENDOR_NETRONOME=y\n# CONFIG_NFP is not set\nCONFIG_NET_VENDOR_8390=y\n# CONFIG_PCMCIA_AXNET is not set\n# CONFIG_NE2K_PCI is not set\n# CONFIG_PCMCIA_PCNET is not set\nCONFIG_NET_VENDOR_NVIDIA=y\nCONFIG_FORCEDETH=y\nCONFIG_NET_VENDOR_OKI=y\n# CONFIG_ETHOC is not set\nCONFIG_NET_VENDOR_PACKET_ENGINES=y\n# CONFIG_HAMACHI is not set\n# CONFIG_YELLOWFIN is not set\nCONFIG_NET_VENDOR_PENSANDO=y\n# CONFIG_IONIC is not set\nCONFIG_NET_VENDOR_QLOGIC=y\n# CONFIG_QLA3XXX is not set\n# CONFIG_QLCNIC is not set\n# CONFIG_NETXEN_NIC is not set\n# CONFIG_QED is not set\nCONFIG_NET_VENDOR_BROCADE=y\n# CONFIG_BNA is not set\nCONFIG_NET_VENDOR_QUALCOMM=y\n# CONFIG_QCOM_EMAC is not set\n# CONFIG_RMNET is not set\nCONFIG_NET_VENDOR_RDC=y\n# CONFIG_R6040 is not set\nCONFIG_NET_VENDOR_REALTEK=y\n# CONFIG_8139CP is not set\nCONFIG_8139TOO=y\nCONFIG_8139TOO_PIO=y\n# CONFIG_8139TOO_TUNE_TWISTER is not set\n# CONFIG_8139TOO_8129 is not set\n# CONFIG_8139_OLD_RX_RESET is not set\nCONFIG_R8169=y\n# CONFIG_RTASE is not set\nCONFIG_NET_VENDOR_RENESAS=y\nCONFIG_NET_VENDOR_ROCKER=y\nCONFIG_NET_VENDOR_SAMSUNG=y\n# CONFIG_SXGBE_ETH is not set\nCONFIG_NET_VENDOR_SEEQ=y\nCONFIG_NET_VENDOR_SILAN=y\n# CONFIG_SC92031 is not set\nCONFIG_NET_VENDOR_SIS=y\n# CONFIG_SIS900 is not set\n# CONFIG_SIS190 is not set\nCONFIG_NET_VENDOR_SOLARFLARE=y\n# CONFIG_SFC is not set\n# CONFIG_SFC_FALCON is not set\n# CONFIG_SFC_SIENA is not set\nCONFIG_NET_VENDOR_SMSC=y\n# CONFIG_PCMCIA_SMC91C92 is not set\n# CONFIG_EPIC100 is not set\n# CONFIG_SMSC911X is not set\n# CONFIG_SMSC9420 is not set\nCONFIG_NET_VENDOR_SOCIONEXT=y\nCONFIG_NET_VENDOR_STMICRO=y\n# CONFIG_STMMAC_ETH is not set\nCONFIG_NET_VENDOR_SUN=y\n# CONFIG_HAPPYMEAL is not set\n# CONFIG_SUNGEM is not set\n# CONFIG_CASSINI is not set\n# CONFIG_NIU is not set\nCONFIG_NET_VENDOR_SYNOPSYS=y\n# CONFIG_DWC_XLGMAC is not set\nCONFIG_NET_VENDOR_TEHUTI=y\n# CONFIG_TEHUTI is not set\n# CONFIG_TEHUTI_TN40 is not set\nCONFIG_NET_VENDOR_TI=y\n# CONFIG_TI_CPSW_PHY_SEL is not set\n# CONFIG_TLAN is not set\n# CONFIG_NET_VENDOR_VERTEXCOM is not set\nCONFIG_NET_VENDOR_VIA=y\n# CONFIG_VIA_RHINE is not set\n# CONFIG_VIA_VELOCITY is not set\n# CONFIG_NET_VENDOR_WANGXUN is not set\nCONFIG_NET_VENDOR_WIZNET=y\n# CONFIG_WIZNET_W5100 is not set\n# CONFIG_WIZNET_W5300 is not set\nCONFIG_NET_VENDOR_XILINX=y\n# CONFIG_XILINX_EMACLITE is not set\n# CONFIG_XILINX_LL_TEMAC is not set\nCONFIG_NET_VENDOR_XIRCOM=y\n# CONFIG_PCMCIA_XIRC2PS is not set\n# CONFIG_FDDI is not set\n# CONFIG_HIPPI is not set\nCONFIG_MDIO_BUS=y\nCONFIG_PHYLIB=y\nCONFIG_SWPHY=y\nCONFIG_FIXED_PHY=y\n\n#\n# MII PHY device drivers\n#\n# CONFIG_AS21XXX_PHY is not set\n# CONFIG_AIR_EN8811H_PHY is not set\n# CONFIG_AMD_PHY is not set\n# CONFIG_ADIN_PHY is not set\n# CONFIG_ADIN1100_PHY is not set\n# CONFIG_AQUANTIA_PHY is not set\n# CONFIG_AX88796B_PHY is not set\n# CONFIG_BROADCOM_PHY is not set\n# CONFIG_BCM54140_PHY is not set\n# CONFIG_BCM7XXX_PHY is not set\n# CONFIG_BCM84881_PHY is not set\n# CONFIG_BCM87XX_PHY is not set\n# CONFIG_CICADA_PHY is not set\n# CONFIG_CORTINA_PHY is not set\n# CONFIG_DAVICOM_PHY is not set\n# CONFIG_ICPLUS_PHY is not set\n# CONFIG_LXT_PHY is not set\n# CONFIG_INTEL_XWAY_PHY is not set\n# CONFIG_LSI_ET1011C_PHY is not set\n# CONFIG_MARVELL_PHY is not set\n# CONFIG_MARVELL_10G_PHY is not set\n# CONFIG_MARVELL_88Q2XXX_PHY is not set\n# CONFIG_MARVELL_88X2222_PHY is not set\n# CONFIG_MAXLINEAR_GPHY is not set\n# CONFIG_MAXLINEAR_86110_PHY is not set\n# CONFIG_MEDIATEK_GE_PHY is not set\n# CONFIG_MICREL_PHY is not set\n# CONFIG_MICROCHIP_T1S_PHY is not set\n# CONFIG_MICROCHIP_PHY is not set\n# CONFIG_MICROCHIP_T1_PHY is not set\n# CONFIG_MICROSEMI_PHY is not set\n# CONFIG_MOTORCOMM_PHY is not set\n# CONFIG_NATIONAL_PHY is not set\n# CONFIG_NXP_CBTX_PHY is not set\n# CONFIG_NXP_C45_TJA11XX_PHY is not set\n# CONFIG_NXP_TJA11XX_PHY is not set\n# CONFIG_NCN26000_PHY is not set\n# CONFIG_QCA83XX_PHY is not set\n# CONFIG_QCA808X_PHY is not set\n# CONFIG_QSEMI_PHY is not set\nCONFIG_REALTEK_PHY=y\nCONFIG_REALTEK_PHY_HWMON=y\n# CONFIG_RENESAS_PHY is not set\n# CONFIG_ROCKCHIP_PHY is not set\n# CONFIG_SMSC_PHY is not set\n# CONFIG_STE10XP is not set\n# CONFIG_TERANETICS_PHY is not set\n# CONFIG_DP83822_PHY is not set\n# CONFIG_DP83TC811_PHY is not set\n# CONFIG_DP83848_PHY is not set\n# CONFIG_DP83867_PHY is not set\n# CONFIG_DP83869_PHY is not set\n# CONFIG_DP83TD510_PHY is not set\n# CONFIG_DP83TG720_PHY is not set\n# CONFIG_VITESSE_PHY is not set\n# CONFIG_XILINX_GMII2RGMII is not set\nCONFIG_FWNODE_MDIO=y\nCONFIG_ACPI_MDIO=y\n# CONFIG_MDIO_BITBANG is not set\n# CONFIG_MDIO_BCM_UNIMAC is not set\n# CONFIG_MDIO_MVUSB is not set\n# CONFIG_MDIO_THUNDER is not set\n\n#\n# MDIO Multiplexers\n#\n\n#\n# PCS device drivers\n#\n# CONFIG_PCS_XPCS is not set\n# end of PCS device drivers\n\nCONFIG_PPP=y\n# CONFIG_PPP_BSDCOMP is not set\n# CONFIG_PPP_DEFLATE is not set\n# CONFIG_PPP_FILTER is not set\n# CONFIG_PPP_MPPE is not set\n# CONFIG_PPP_MULTILINK is not set\n# CONFIG_PPPOE is not set\nCONFIG_PPPOE_HASH_BITS=4\n# CONFIG_PPTP is not set\nCONFIG_PPP_ASYNC=y\nCONFIG_PPP_SYNC_TTY=y\n# CONFIG_SLIP is not set\nCONFIG_SLHC=y\nCONFIG_USB_NET_DRIVERS=y\n# CONFIG_USB_CATC is not set\n# CONFIG_USB_KAWETH is not set\n# CONFIG_USB_PEGASUS is not set\n# CONFIG_USB_RTL8150 is not set\n# CONFIG_USB_RTL8152 is not set\n# CONFIG_USB_LAN78XX is not set\n# CONFIG_USB_USBNET is not set\n# CONFIG_USB_HSO is not set\n# CONFIG_USB_IPHETH is not set\nCONFIG_WLAN=y\nCONFIG_WLAN_VENDOR_ADMTEK=y\n# CONFIG_ADM8211 is not set\nCONFIG_WLAN_VENDOR_ATH=y\n# CONFIG_ATH_DEBUG is not set\n# CONFIG_ATH5K is not set\n# CONFIG_ATH5K_PCI is not set\n# CONFIG_ATH9K is not set\n# CONFIG_ATH9K_HTC is not set\n# CONFIG_CARL9170 is not set\n# CONFIG_ATH6KL is not set\n# CONFIG_AR5523 is not set\n# CONFIG_WIL6210 is not set\n# CONFIG_ATH10K is not set\n# CONFIG_WCN36XX is not set\n# CONFIG_ATH11K is not set\n# CONFIG_ATH12K is not set\nCONFIG_WLAN_VENDOR_ATMEL=y\n# CONFIG_AT76C50X_USB is not set\nCONFIG_WLAN_VENDOR_BROADCOM=y\n# CONFIG_B43 is not set\n# CONFIG_B43LEGACY is not set\n# CONFIG_BRCMSMAC is not set\n# CONFIG_BRCMFMAC is not set\nCONFIG_WLAN_VENDOR_INTEL=y\n# CONFIG_IPW2100 is not set\n# CONFIG_IPW2200 is not set\n# CONFIG_IWLWIFI is not set\nCONFIG_WLAN_VENDOR_INTERSIL=y\n# CONFIG_P54_COMMON is not set\nCONFIG_WLAN_VENDOR_MARVELL=y\n# CONFIG_LIBERTAS is not set\n# CONFIG_LIBERTAS_THINFIRM is not set\n# CONFIG_MWIFIEX is not set\n# CONFIG_MWL8K is not set\nCONFIG_WLAN_VENDOR_MEDIATEK=y\n# CONFIG_MT7601U is not set\n# CONFIG_MT76x0U is not set\n# CONFIG_MT76x0E is not set\n# CONFIG_MT76x2E is not set\n# CONFIG_MT76x2U is not set\n# CONFIG_MT7603E is not set\n# CONFIG_MT7615E is not set\n# CONFIG_MT7663U is not set\n# CONFIG_MT7915E is not set\n# CONFIG_MT7921E is not set\n# CONFIG_MT7921U is not set\n# CONFIG_MT7996E is not set\n# CONFIG_MT7925E is not set\n# CONFIG_MT7925U is not set\nCONFIG_WLAN_VENDOR_MICROCHIP=y\n# CONFIG_WLAN_VENDOR_PURELIFI is not set\nCONFIG_WLAN_VENDOR_RALINK=y\n# CONFIG_RT2X00 is not set\nCONFIG_WLAN_VENDOR_REALTEK=y\n# CONFIG_RTL8180 is not set\n# CONFIG_RTL8187 is not set\nCONFIG_RTL_CARDS=y\n# CONFIG_RTL8192CE is not set\n# CONFIG_RTL8192SE is not set\n# CONFIG_RTL8192DE is not set\n# CONFIG_RTL8723AE is not set\n# CONFIG_RTL8723BE is not set\n# CONFIG_RTL8188EE is not set\n# CONFIG_RTL8192EE is not set\n# CONFIG_RTL8821AE is not set\n# CONFIG_RTL8192CU is not set\n# CONFIG_RTL8192DU is not set\n# CONFIG_RTW88 is not set\n# CONFIG_RTW89 is not set\nCONFIG_WLAN_VENDOR_RSI=y\n# CONFIG_RSI_91X is not set\n# CONFIG_WLAN_VENDOR_SILABS is not set\nCONFIG_WLAN_VENDOR_ST=y\n# CONFIG_CW1200 is not set\nCONFIG_WLAN_VENDOR_TI=y\n# CONFIG_WL1251 is not set\n# CONFIG_WL12XX is not set\n# CONFIG_WL18XX is not set\n# CONFIG_WLCORE is not set\nCONFIG_WLAN_VENDOR_ZYDAS=y\n# CONFIG_ZD1211RW is not set\nCONFIG_WLAN_VENDOR_QUANTENNA=y\n# CONFIG_QTNFMAC_PCIE is not set\n# CONFIG_MAC80211_HWSIM is not set\n# CONFIG_VIRT_WIFI is not set\n# CONFIG_WAN is not set\n\n#\n# Wireless WAN\n#\n# CONFIG_WWAN is not set\n# end of Wireless WAN\n\n# CONFIG_VMXNET3 is not set\n# CONFIG_FUJITSU_ES is not set\nCONFIG_NETDEVSIM=y\nCONFIG_NET_FAILOVER=y\n# CONFIG_ISDN is not set\n\n#\n# Input device support\n#\nCONFIG_INPUT=y\nCONFIG_INPUT_FF_MEMLESS=y\nCONFIG_INPUT_SPARSEKMAP=y\n# CONFIG_INPUT_MATRIXKMAP is not set\nCONFIG_INPUT_VIVALDIFMAP=y\n\n#\n# Userland interfaces\n#\n# CONFIG_INPUT_MOUSEDEV is not set\n# CONFIG_INPUT_JOYDEV is not set\nCONFIG_INPUT_EVDEV=y\n\n#\n# Input Device Drivers\n#\nCONFIG_INPUT_KEYBOARD=y\n# CONFIG_KEYBOARD_ADP5588 is not set\nCONFIG_KEYBOARD_ATKBD=y\n# CONFIG_KEYBOARD_QT1050 is not set\n# CONFIG_KEYBOARD_QT1070 is not set\n# CONFIG_KEYBOARD_QT2160 is not set\n# CONFIG_KEYBOARD_DLINK_DIR685 is not set\n# CONFIG_KEYBOARD_LKKBD is not set\n# CONFIG_KEYBOARD_TCA8418 is not set\n# CONFIG_KEYBOARD_LM8333 is not set\n# CONFIG_KEYBOARD_MAX7359 is not set\n# CONFIG_KEYBOARD_MPR121 is not set\n# CONFIG_KEYBOARD_NEWTON is not set\n# CONFIG_KEYBOARD_OPENCORES is not set\n# CONFIG_KEYBOARD_SAMSUNG is not set\n# CONFIG_KEYBOARD_STOWAWAY is not set\n# CONFIG_KEYBOARD_SUNKBD is not set\n# CONFIG_KEYBOARD_XTKBD is not set\n# CONFIG_KEYBOARD_CYPRESS_SF is not set\nCONFIG_INPUT_MOUSE=y\nCONFIG_MOUSE_PS2=y\nCONFIG_MOUSE_PS2_ALPS=y\nCONFIG_MOUSE_PS2_BYD=y\nCONFIG_MOUSE_PS2_LOGIPS2PP=y\nCONFIG_MOUSE_PS2_SYNAPTICS=y\nCONFIG_MOUSE_PS2_SYNAPTICS_SMBUS=y\nCONFIG_MOUSE_PS2_CYPRESS=y\nCONFIG_MOUSE_PS2_LIFEBOOK=y\nCONFIG_MOUSE_PS2_TRACKPOINT=y\n# CONFIG_MOUSE_PS2_ELANTECH is not set\n# CONFIG_MOUSE_PS2_SENTELIC is not set\n# CONFIG_MOUSE_PS2_TOUCHKIT is not set\nCONFIG_MOUSE_PS2_FOCALTECH=y\n# CONFIG_MOUSE_PS2_VMMOUSE is not set\nCONFIG_MOUSE_PS2_SMBUS=y\n# CONFIG_MOUSE_SERIAL is not set\n# CONFIG_MOUSE_APPLETOUCH is not set\n# CONFIG_MOUSE_BCM5974 is not set\n# CONFIG_MOUSE_CYAPA is not set\n# CONFIG_MOUSE_ELAN_I2C is not set\n# CONFIG_MOUSE_VSXXXAA is not set\n# CONFIG_MOUSE_SYNAPTICS_I2C is not set\n# CONFIG_MOUSE_SYNAPTICS_USB is not set\nCONFIG_INPUT_JOYSTICK=y\n# CONFIG_JOYSTICK_ANALOG is not set\n# CONFIG_JOYSTICK_A3D is not set\n# CONFIG_JOYSTICK_ADI is not set\n# CONFIG_JOYSTICK_COBRA is not set\n# CONFIG_JOYSTICK_GF2K is not set\n# CONFIG_JOYSTICK_GRIP is not set\n# CONFIG_JOYSTICK_GRIP_MP is not set\n# CONFIG_JOYSTICK_GUILLEMOT is not set\n# CONFIG_JOYSTICK_INTERACT is not set\n# CONFIG_JOYSTICK_SIDEWINDER is not set\n# CONFIG_JOYSTICK_TMDC is not set\n# CONFIG_JOYSTICK_IFORCE is not set\n# CONFIG_JOYSTICK_WARRIOR is not set\n# CONFIG_JOYSTICK_MAGELLAN is not set\n# CONFIG_JOYSTICK_SPACEORB is not set\n# CONFIG_JOYSTICK_SPACEBALL is not set\n# CONFIG_JOYSTICK_STINGER is not set\n# CONFIG_JOYSTICK_TWIDJOY is not set\n# CONFIG_JOYSTICK_ZHENHUA is not set\n# CONFIG_JOYSTICK_AS5011 is not set\n# CONFIG_JOYSTICK_JOYDUMP is not set\n# CONFIG_JOYSTICK_XPAD is not set\n# CONFIG_JOYSTICK_PXRC is not set\n# CONFIG_JOYSTICK_QWIIC is not set\n# CONFIG_JOYSTICK_FSIA6B is not set\n# CONFIG_JOYSTICK_SENSEHAT is not set\n# CONFIG_JOYSTICK_SEESAW is not set\nCONFIG_INPUT_TABLET=y\n# CONFIG_TABLET_USB_ACECAD is not set\n# CONFIG_TABLET_USB_AIPTEK is not set\n# CONFIG_TABLET_USB_HANWANG is not set\n# CONFIG_TABLET_USB_KBTAB is not set\n# CONFIG_TABLET_USB_PEGASUS is not set\n# CONFIG_TABLET_SERIAL_WACOM4 is not set\nCONFIG_INPUT_TOUCHSCREEN=y\n# CONFIG_TOUCHSCREEN_AD7879 is not set\n# CONFIG_TOUCHSCREEN_ATMEL_MXT is not set\n# CONFIG_TOUCHSCREEN_BU21013 is not set\n# CONFIG_TOUCHSCREEN_BU21029 is not set\n# CONFIG_TOUCHSCREEN_CHIPONE_ICN8505 is not set\n# CONFIG_TOUCHSCREEN_CY8CTMA140 is not set\n# CONFIG_TOUCHSCREEN_CYTTSP_CORE is not set\n# CONFIG_TOUCHSCREEN_CYTTSP5 is not set\n# CONFIG_TOUCHSCREEN_DYNAPRO is not set\n# CONFIG_TOUCHSCREEN_HAMPSHIRE is not set\n# CONFIG_TOUCHSCREEN_EETI is not set\n# CONFIG_TOUCHSCREEN_EGALAX_SERIAL is not set\n# CONFIG_TOUCHSCREEN_EXC3000 is not set\n# CONFIG_TOUCHSCREEN_FUJITSU is not set\n# CONFIG_TOUCHSCREEN_GOODIX_BERLIN_I2C is not set\n# CONFIG_TOUCHSCREEN_HIDEEP is not set\n# CONFIG_TOUCHSCREEN_HIMAX_HX852X is not set\n# CONFIG_TOUCHSCREEN_HYCON_HY46XX is not set\n# CONFIG_TOUCHSCREEN_HYNITRON_CSTXXX is not set\n# CONFIG_TOUCHSCREEN_HYNITRON_CST816X is not set\n# CONFIG_TOUCHSCREEN_ILI210X is not set\n# CONFIG_TOUCHSCREEN_ILITEK is not set\n# CONFIG_TOUCHSCREEN_S6SY761 is not set\n# CONFIG_TOUCHSCREEN_GUNZE is not set\n# CONFIG_TOUCHSCREEN_EKTF2127 is not set\n# CONFIG_TOUCHSCREEN_ELAN is not set\n# CONFIG_TOUCHSCREEN_ELO is not set\n# CONFIG_TOUCHSCREEN_WACOM_W8001 is not set\n# CONFIG_TOUCHSCREEN_WACOM_I2C is not set\n# CONFIG_TOUCHSCREEN_MAX11801 is not set\n# CONFIG_TOUCHSCREEN_MMS114 is not set\n# CONFIG_TOUCHSCREEN_MELFAS_MIP4 is not set\n# CONFIG_TOUCHSCREEN_MTOUCH is not set\n# CONFIG_TOUCHSCREEN_NOVATEK_NVT_TS is not set\n# CONFIG_TOUCHSCREEN_IMAGIS is not set\n# CONFIG_TOUCHSCREEN_INEXIO is not set\n# CONFIG_TOUCHSCREEN_PENMOUNT is not set\n# CONFIG_TOUCHSCREEN_EDT_FT5X06 is not set\n# CONFIG_TOUCHSCREEN_TOUCHRIGHT is not set\n# CONFIG_TOUCHSCREEN_TOUCHWIN is not set\n# CONFIG_TOUCHSCREEN_PIXCIR is not set\n# CONFIG_TOUCHSCREEN_WDT87XX_I2C is not set\n# CONFIG_TOUCHSCREEN_USB_COMPOSITE is not set\n# CONFIG_TOUCHSCREEN_TOUCHIT213 is not set\n# CONFIG_TOUCHSCREEN_TSC_SERIO is not set\n# CONFIG_TOUCHSCREEN_TSC2004 is not set\n# CONFIG_TOUCHSCREEN_TSC2007 is not set\n# CONFIG_TOUCHSCREEN_SILEAD is not set\n# CONFIG_TOUCHSCREEN_ST1232 is not set\n# CONFIG_TOUCHSCREEN_SX8654 is not set\n# CONFIG_TOUCHSCREEN_TPS6507X is not set\n# CONFIG_TOUCHSCREEN_ZET6223 is not set\n# CONFIG_TOUCHSCREEN_ROHM_BU21023 is not set\n# CONFIG_TOUCHSCREEN_IQS5XX is not set\n# CONFIG_TOUCHSCREEN_IQS7211 is not set\n# CONFIG_TOUCHSCREEN_ZINITIX is not set\n# CONFIG_TOUCHSCREEN_HIMAX_HX83112B is not set\nCONFIG_INPUT_MISC=y\n# CONFIG_INPUT_AD714X is not set\n# CONFIG_INPUT_AW86927 is not set\n# CONFIG_INPUT_BMA150 is not set\n# CONFIG_INPUT_E3X0_BUTTON is not set\n# CONFIG_INPUT_PCSPKR is not set\n# CONFIG_INPUT_MMA8450 is not set\n# CONFIG_INPUT_ATLAS_BTNS is not set\n# CONFIG_INPUT_ATI_REMOTE2 is not set\n# CONFIG_INPUT_KEYSPAN_REMOTE is not set\n# CONFIG_INPUT_KXTJ9 is not set\n# CONFIG_INPUT_POWERMATE is not set\n# CONFIG_INPUT_YEALINK is not set\n# CONFIG_INPUT_CM109 is not set\n# CONFIG_INPUT_UINPUT is not set\n# CONFIG_INPUT_PCF8574 is not set\n# CONFIG_INPUT_DA7280_HAPTICS is not set\n# CONFIG_INPUT_ADXL34X is not set\n# CONFIG_INPUT_IQS269A is not set\n# CONFIG_INPUT_IQS626A is not set\n# CONFIG_INPUT_IQS7222 is not set\n# CONFIG_INPUT_CMA3000 is not set\n# CONFIG_INPUT_IDEAPAD_SLIDEBAR is not set\n# CONFIG_INPUT_DRV2665_HAPTICS is not set\n# CONFIG_INPUT_DRV2667_HAPTICS is not set\n# CONFIG_RMI4_CORE is not set\n\n#\n# Hardware I/O ports\n#\nCONFIG_SERIO=y\nCONFIG_ARCH_MIGHT_HAVE_PC_SERIO=y\nCONFIG_SERIO_I8042=y\nCONFIG_SERIO_SERPORT=y\n# CONFIG_SERIO_CT82C710 is not set\n# CONFIG_SERIO_PCIPS2 is not set\nCONFIG_SERIO_LIBPS2=y\n# CONFIG_SERIO_RAW is not set\n# CONFIG_SERIO_ALTERA_PS2 is not set\n# CONFIG_SERIO_PS2MULT is not set\n# CONFIG_SERIO_ARC_PS2 is not set\n# CONFIG_USERIO is not set\n# CONFIG_GAMEPORT is not set\n# end of Hardware I/O ports\n# end of Input device support\n\n#\n# Character devices\n#\nCONFIG_TTY=y\nCONFIG_VT=y\nCONFIG_CONSOLE_TRANSLATIONS=y\nCONFIG_VT_CONSOLE=y\nCONFIG_VT_CONSOLE_SLEEP=y\nCONFIG_VT_HW_CONSOLE_BINDING=y\nCONFIG_UNIX98_PTYS=y\n# CONFIG_LEGACY_PTYS is not set\nCONFIG_LEGACY_TIOCSTI=y\nCONFIG_LDISC_AUTOLOAD=y\n\n#\n# Serial drivers\n#\nCONFIG_SERIAL_EARLYCON=y\nCONFIG_SERIAL_8250=y\nCONFIG_SERIAL_8250_PNP=y\n# CONFIG_SERIAL_8250_16550A_VARIANTS is not set\n# CONFIG_SERIAL_8250_FINTEK is not set\nCONFIG_SERIAL_8250_CONSOLE=y\nCONFIG_SERIAL_8250_DMA=y\nCONFIG_SERIAL_8250_PCILIB=y\nCONFIG_SERIAL_8250_PCI=y\nCONFIG_SERIAL_8250_EXAR=y\n# CONFIG_SERIAL_8250_CS is not set\nCONFIG_SERIAL_8250_NR_UARTS=32\nCONFIG_SERIAL_8250_RUNTIME_UARTS=4\nCONFIG_SERIAL_8250_EXTENDED=y\nCONFIG_SERIAL_8250_MANY_PORTS=y\n# CONFIG_SERIAL_8250_PCI1XXXX is not set\nCONFIG_SERIAL_8250_SHARE_IRQ=y\nCONFIG_SERIAL_8250_DETECT_IRQ=y\nCONFIG_SERIAL_8250_RSA=y\nCONFIG_SERIAL_8250_DWLIB=y\n# CONFIG_SERIAL_8250_DW is not set\n# CONFIG_SERIAL_8250_RT288X is not set\nCONFIG_SERIAL_8250_LPSS=y\nCONFIG_SERIAL_8250_MID=y\n# CONFIG_SERIAL_8250_PERICOM is not set\n# CONFIG_SERIAL_8250_NI is not set\n\n#\n# Non-8250 serial port support\n#\n# CONFIG_SERIAL_UARTLITE is not set\nCONFIG_SERIAL_CORE=y\nCONFIG_SERIAL_CORE_CONSOLE=y\n# CONFIG_SERIAL_JSM is not set\n# CONFIG_SERIAL_LANTIQ is not set\n# CONFIG_SERIAL_SCCNXP is not set\n# CONFIG_SERIAL_SC16IS7XX is not set\n# CONFIG_SERIAL_ALTERA_JTAGUART is not set\n# CONFIG_SERIAL_ALTERA_UART is not set\n# CONFIG_SERIAL_ARC is not set\n# CONFIG_SERIAL_RP2 is not set\n# CONFIG_SERIAL_FSL_LPUART is not set\n# CONFIG_SERIAL_FSL_LINFLEXUART is not set\n# CONFIG_SERIAL_SPRD is not set\n# end of Serial drivers\n\nCONFIG_SERIAL_NONSTANDARD=y\n# CONFIG_MOXA_INTELLIO is not set\n# CONFIG_MOXA_SMARTIO is not set\n# CONFIG_N_HDLC is not set\n# CONFIG_IPWIRELESS is not set\n# CONFIG_N_GSM is not set\n# CONFIG_NOZOMI is not set\n# CONFIG_NULL_TTY is not set\n# CONFIG_SERIAL_DEV_BUS is not set\n# CONFIG_TTY_PRINTK is not set\n# CONFIG_VIRTIO_CONSOLE is not set\n# CONFIG_IPMI_HANDLER is not set\nCONFIG_HW_RANDOM=y\n# CONFIG_HW_RANDOM_TIMERIOMEM is not set\n# CONFIG_HW_RANDOM_INTEL is not set\n# CONFIG_HW_RANDOM_AMD is not set\n# CONFIG_HW_RANDOM_BA431 is not set\nCONFIG_HW_RANDOM_VIA=y\n# CONFIG_HW_RANDOM_VIRTIO is not set\n# CONFIG_HW_RANDOM_XIPHERA is not set\n# CONFIG_APPLICOM is not set\n# CONFIG_MWAVE is not set\nCONFIG_DEVMEM=y\nCONFIG_NVRAM=y\nCONFIG_DEVPORT=y\nCONFIG_HPET=y\n# CONFIG_HPET_MMAP is not set\n# CONFIG_HANGCHECK_TIMER is not set\nCONFIG_TCG_TPM=y\n# CONFIG_TCG_TPM2_HMAC is not set\nCONFIG_HW_RANDOM_TPM=y\nCONFIG_TCG_TIS_CORE=y\nCONFIG_TCG_TIS=y\n# CONFIG_TCG_TIS_I2C is not set\n# CONFIG_TCG_TIS_I2C_CR50 is not set\n# CONFIG_TCG_TIS_I2C_ATMEL is not set\n# CONFIG_TCG_TIS_I2C_INFINEON is not set\n# CONFIG_TCG_TIS_I2C_NUVOTON is not set\n# CONFIG_TCG_NSC is not set\n# CONFIG_TCG_ATMEL is not set\n# CONFIG_TCG_INFINEON is not set\nCONFIG_TCG_CRB=y\n# CONFIG_TCG_VTPM_PROXY is not set\n# CONFIG_TCG_TIS_ST33ZP24_I2C is not set\n# CONFIG_TELCLOCK is not set\n# CONFIG_XILLYBUS is not set\n# CONFIG_XILLYUSB is not set\n# end of Character devices\n\n#\n# I2C support\n#\nCONFIG_I2C=y\nCONFIG_ACPI_I2C_OPREGION=y\nCONFIG_I2C_BOARDINFO=y\n# CONFIG_I2C_CHARDEV is not set\n# CONFIG_I2C_MUX is not set\nCONFIG_I2C_HELPER_AUTO=y\nCONFIG_I2C_SMBUS=y\n\n#\n# I2C Hardware Bus support\n#\n\n#\n# PC SMBus host controller drivers\n#\n# CONFIG_I2C_ALI1535 is not set\n# CONFIG_I2C_ALI1563 is not set\n# CONFIG_I2C_ALI15X3 is not set\n# CONFIG_I2C_AMD756 is not set\n# CONFIG_I2C_AMD8111 is not set\n# CONFIG_I2C_AMD_MP2 is not set\nCONFIG_I2C_I801=y\n# CONFIG_I2C_ISCH is not set\n# CONFIG_I2C_ISMT is not set\n# CONFIG_I2C_PIIX4 is not set\n# CONFIG_I2C_NFORCE2 is not set\n# CONFIG_I2C_NVIDIA_GPU is not set\n# CONFIG_I2C_SIS5595 is not set\n# CONFIG_I2C_SIS630 is not set\n# CONFIG_I2C_SIS96X is not set\n# CONFIG_I2C_VIA is not set\n# CONFIG_I2C_VIAPRO is not set\n# CONFIG_I2C_ZHAOXIN is not set\n\n#\n# ACPI drivers\n#\n# CONFIG_I2C_SCMI is not set\n\n#\n# I2C system bus drivers (mostly embedded / system-on-chip)\n#\n# CONFIG_I2C_DESIGNWARE_CORE is not set\n# CONFIG_I2C_EMEV2 is not set\n# CONFIG_I2C_OCORES is not set\n# CONFIG_I2C_PCA_PLATFORM is not set\n# CONFIG_I2C_SIMTEC is not set\n# CONFIG_I2C_XILINX is not set\n\n#\n# External I2C/SMBus adapter drivers\n#\n# CONFIG_I2C_DIOLAN_U2C is not set\n# CONFIG_I2C_CP2615 is not set\n# CONFIG_I2C_PCI1XXXX is not set\n# CONFIG_I2C_ROBOTFUZZ_OSIF is not set\n# CONFIG_I2C_TAOS_EVM is not set\n# CONFIG_I2C_TINY_USB is not set\n\n#\n# Other I2C/SMBus bus drivers\n#\n# CONFIG_I2C_MLXCPLD is not set\n# CONFIG_I2C_VIRTIO is not set\n# end of I2C Hardware Bus support\n\n# CONFIG_I2C_STUB is not set\n# CONFIG_I2C_SLAVE is not set\n# CONFIG_I2C_DEBUG_CORE is not set\n# CONFIG_I2C_DEBUG_ALGO is not set\n# CONFIG_I2C_DEBUG_BUS is not set\n# end of I2C support\n\n# CONFIG_I3C is not set\n# CONFIG_SPI is not set\n# CONFIG_SPMI is not set\n# CONFIG_HSI is not set\nCONFIG_PPS=y\n# CONFIG_PPS_DEBUG is not set\n\n#\n# PPS clients support\n#\n# CONFIG_PPS_CLIENT_KTIMER is not set\n# CONFIG_PPS_CLIENT_LDISC is not set\n# CONFIG_PPS_CLIENT_GPIO is not set\n# CONFIG_PPS_GENERATOR is not set\n\n#\n# PTP clock support\n#\nCONFIG_PTP_1588_CLOCK=y\nCONFIG_PTP_1588_CLOCK_OPTIONAL=y\n\n#\n# Enable PHYLIB and NETWORK_PHY_TIMESTAMPING to see the additional clocks.\n#\nCONFIG_PTP_1588_CLOCK_KVM=y\nCONFIG_PTP_1588_CLOCK_VMCLOCK=y\n# CONFIG_PTP_1588_CLOCK_IDT82P33 is not set\n# CONFIG_PTP_1588_CLOCK_IDTCM is not set\n# CONFIG_PTP_1588_CLOCK_FC3W is not set\n# CONFIG_PTP_1588_CLOCK_MOCK is not set\n# CONFIG_PTP_1588_CLOCK_VMW is not set\n# CONFIG_PTP_NETC_V4_TIMER is not set\n# end of PTP clock support\n\n#\n# DPLL device support\n#\n# CONFIG_ZL3073X_I2C is not set\n# end of DPLL device support\n\nCONFIG_PINCTRL=y\n# CONFIG_DEBUG_PINCTRL is not set\n# CONFIG_PINCTRL_AMD is not set\n# CONFIG_PINCTRL_CY8C95X0 is not set\n# CONFIG_PINCTRL_MCP23S08 is not set\n# CONFIG_PINCTRL_SX150X is not set\n\n#\n# Intel pinctrl drivers\n#\n# CONFIG_PINCTRL_BAYTRAIL is not set\n# CONFIG_PINCTRL_CHERRYVIEW is not set\n# CONFIG_PINCTRL_LYNXPOINT is not set\n# CONFIG_PINCTRL_INTEL_PLATFORM is not set\n# CONFIG_PINCTRL_ALDERLAKE is not set\n# CONFIG_PINCTRL_BROXTON is not set\n# CONFIG_PINCTRL_CANNONLAKE is not set\n# CONFIG_PINCTRL_CEDARFORK is not set\n# CONFIG_PINCTRL_DENVERTON is not set\n# CONFIG_PINCTRL_ELKHARTLAKE is not set\n# CONFIG_PINCTRL_EMMITSBURG is not set\n# CONFIG_PINCTRL_GEMINILAKE is not set\n# CONFIG_PINCTRL_ICELAKE is not set\n# CONFIG_PINCTRL_JASPERLAKE is not set\n# CONFIG_PINCTRL_LAKEFIELD is not set\n# CONFIG_PINCTRL_LEWISBURG is not set\n# CONFIG_PINCTRL_METEORLAKE is not set\n# CONFIG_PINCTRL_METEORPOINT is not set\n# CONFIG_PINCTRL_SUNRISEPOINT is not set\n# CONFIG_PINCTRL_TIGERLAKE is not set\n# end of Intel pinctrl drivers\n\n#\n# Renesas pinctrl drivers\n#\n# end of Renesas pinctrl drivers\n\nCONFIG_GPIOLIB_LEGACY=y\n# CONFIG_GPIOLIB is not set\n# CONFIG_W1 is not set\n# CONFIG_POWER_RESET is not set\n# CONFIG_POWER_SEQUENCING is not set\nCONFIG_POWER_SUPPLY=y\n# CONFIG_POWER_SUPPLY_DEBUG is not set\nCONFIG_POWER_SUPPLY_HWMON=y\n# CONFIG_IP5XXX_POWER is not set\n# CONFIG_TEST_POWER is not set\n# CONFIG_CHARGER_ADP5061 is not set\n# CONFIG_BATTERY_CW2015 is not set\n# CONFIG_BATTERY_DS2780 is not set\n# CONFIG_BATTERY_DS2781 is not set\n# CONFIG_BATTERY_DS2782 is not set\n# CONFIG_BATTERY_SAMSUNG_SDI is not set\n# CONFIG_BATTERY_SBS is not set\n# CONFIG_CHARGER_SBS is not set\n# CONFIG_BATTERY_BQ27XXX is not set\n# CONFIG_BATTERY_MAX17042 is not set\n# CONFIG_BATTERY_MAX1720X is not set\n# CONFIG_CHARGER_MAX8903 is not set\n# CONFIG_CHARGER_LP8727 is not set\n# CONFIG_CHARGER_LTC4162L is not set\n# CONFIG_CHARGER_MAX77976 is not set\n# CONFIG_CHARGER_MAX8971 is not set\n# CONFIG_CHARGER_BQ2415X is not set\n# CONFIG_BATTERY_GAUGE_LTC2941 is not set\n# CONFIG_BATTERY_GOLDFISH is not set\n# CONFIG_BATTERY_RT5033 is not set\n# CONFIG_CHARGER_RT9756 is not set\n# CONFIG_CHARGER_BD99954 is not set\n# CONFIG_BATTERY_UG3105 is not set\n# CONFIG_FUEL_GAUGE_MM8013 is not set\nCONFIG_HWMON=y\n# CONFIG_HWMON_DEBUG_CHIP is not set\n\n#\n# Native drivers\n#\n# CONFIG_SENSORS_ABITUGURU is not set\n# CONFIG_SENSORS_ABITUGURU3 is not set\n# CONFIG_SENSORS_AD7414 is not set\n# CONFIG_SENSORS_AD7418 is not set\n# CONFIG_SENSORS_ADM1025 is not set\n# CONFIG_SENSORS_ADM1026 is not set\n# CONFIG_SENSORS_ADM1029 is not set\n# CONFIG_SENSORS_ADM1031 is not set\n# CONFIG_SENSORS_ADM1177 is not set\n# CONFIG_SENSORS_ADM9240 is not set\n# CONFIG_SENSORS_ADT7410 is not set\n# CONFIG_SENSORS_ADT7411 is not set\n# CONFIG_SENSORS_ADT7462 is not set\n# CONFIG_SENSORS_ADT7470 is not set\n# CONFIG_SENSORS_ADT7475 is not set\n# CONFIG_SENSORS_AHT10 is not set\n# CONFIG_SENSORS_AQUACOMPUTER_D5NEXT is not set\n# CONFIG_SENSORS_AS370 is not set\n# CONFIG_SENSORS_ASC7621 is not set\n# CONFIG_SENSORS_ASUS_ROG_RYUJIN is not set\n# CONFIG_SENSORS_AXI_FAN_CONTROL is not set\n# CONFIG_SENSORS_K8TEMP is not set\n# CONFIG_SENSORS_K10TEMP is not set\n# CONFIG_SENSORS_FAM15H_POWER is not set\n# CONFIG_SENSORS_APPLESMC is not set\n# CONFIG_SENSORS_ASB100 is not set\n# CONFIG_SENSORS_ATXP1 is not set\n# CONFIG_SENSORS_CHIPCAP2 is not set\n# CONFIG_SENSORS_CORSAIR_CPRO is not set\n# CONFIG_SENSORS_CORSAIR_PSU is not set\n# CONFIG_SENSORS_DRIVETEMP is not set\n# CONFIG_SENSORS_DS620 is not set\n# CONFIG_SENSORS_DS1621 is not set\n# CONFIG_SENSORS_I5K_AMB is not set\n# CONFIG_SENSORS_F71805F is not set\n# CONFIG_SENSORS_F71882FG is not set\n# CONFIG_SENSORS_F75375S is not set\n# CONFIG_SENSORS_FSCHMD is not set\n# CONFIG_SENSORS_FTSTEUTATES is not set\n# CONFIG_SENSORS_GIGABYTE_WATERFORCE is not set\n# CONFIG_SENSORS_GL518SM is not set\n# CONFIG_SENSORS_GL520SM is not set\n# CONFIG_SENSORS_GPD is not set\n# CONFIG_SENSORS_G760A is not set\n# CONFIG_SENSORS_G762 is not set\n# CONFIG_SENSORS_HIH6130 is not set\n# CONFIG_SENSORS_HS3001 is not set\n# CONFIG_SENSORS_HTU31 is not set\n# CONFIG_SENSORS_I5500 is not set\n# CONFIG_SENSORS_CORETEMP is not set\n# CONFIG_SENSORS_ISL28022 is not set\n# CONFIG_SENSORS_IT87 is not set\n# CONFIG_SENSORS_JC42 is not set\n# CONFIG_SENSORS_POWERZ is not set\n# CONFIG_SENSORS_POWR1220 is not set\n# CONFIG_SENSORS_LENOVO_EC is not set\n# CONFIG_SENSORS_LINEAGE is not set\n# CONFIG_SENSORS_LTC2945 is not set\n# CONFIG_SENSORS_LTC2947_I2C is not set\n# CONFIG_SENSORS_LTC2990 is not set\n# CONFIG_SENSORS_LTC2991 is not set\n# CONFIG_SENSORS_LTC4151 is not set\n# CONFIG_SENSORS_LTC4215 is not set\n# CONFIG_SENSORS_LTC4222 is not set\n# CONFIG_SENSORS_LTC4245 is not set\n# CONFIG_SENSORS_LTC4260 is not set\n# CONFIG_SENSORS_LTC4261 is not set\n# CONFIG_SENSORS_LTC4282 is not set\n# CONFIG_SENSORS_MAX127 is not set\n# CONFIG_SENSORS_MAX16065 is not set\n# CONFIG_SENSORS_MAX1619 is not set\n# CONFIG_SENSORS_MAX1668 is not set\n# CONFIG_SENSORS_MAX197 is not set\n# CONFIG_SENSORS_MAX31730 is not set\n# CONFIG_SENSORS_MAX31760 is not set\n# CONFIG_MAX31827 is not set\n# CONFIG_SENSORS_MAX6620 is not set\n# CONFIG_SENSORS_MAX6621 is not set\n# CONFIG_SENSORS_MAX6639 is not set\n# CONFIG_SENSORS_MAX6650 is not set\n# CONFIG_SENSORS_MAX6697 is not set\n# CONFIG_SENSORS_MAX31790 is not set\n# CONFIG_SENSORS_MC34VR500 is not set\n# CONFIG_SENSORS_MCP3021 is not set\n# CONFIG_SENSORS_TC654 is not set\n# CONFIG_SENSORS_TPS23861 is not set\n# CONFIG_SENSORS_MR75203 is not set\n# CONFIG_SENSORS_LM63 is not set\n# CONFIG_SENSORS_LM73 is not set\n# CONFIG_SENSORS_LM75 is not set\n# CONFIG_SENSORS_LM77 is not set\n# CONFIG_SENSORS_LM78 is not set\n# CONFIG_SENSORS_LM80 is not set\n# CONFIG_SENSORS_LM83 is not set\n# CONFIG_SENSORS_LM85 is not set\n# CONFIG_SENSORS_LM87 is not set\n# CONFIG_SENSORS_LM90 is not set\n# CONFIG_SENSORS_LM92 is not set\n# CONFIG_SENSORS_LM93 is not set\n# CONFIG_SENSORS_LM95234 is not set\n# CONFIG_SENSORS_LM95241 is not set\n# CONFIG_SENSORS_LM95245 is not set\n# CONFIG_SENSORS_PC87360 is not set\n# CONFIG_SENSORS_PC87427 is not set\n# CONFIG_SENSORS_NCT6683 is not set\n# CONFIG_SENSORS_NCT6775 is not set\n# CONFIG_SENSORS_NCT6775_I2C is not set\n# CONFIG_SENSORS_NCT7363 is not set\n# CONFIG_SENSORS_NCT7802 is not set\n# CONFIG_SENSORS_NCT7904 is not set\n# CONFIG_SENSORS_NPCM7XX is not set\n# CONFIG_SENSORS_NZXT_KRAKEN2 is not set\n# CONFIG_SENSORS_NZXT_KRAKEN3 is not set\n# CONFIG_SENSORS_NZXT_SMART2 is not set\n# CONFIG_SENSORS_OCC_P8_I2C is not set\n# CONFIG_SENSORS_PCF8591 is not set\n# CONFIG_PMBUS is not set\n# CONFIG_SENSORS_PT5161L is not set\n# CONFIG_SENSORS_SBTSI is not set\n# CONFIG_SENSORS_SHT21 is not set\n# CONFIG_SENSORS_SHT3x is not set\n# CONFIG_SENSORS_SHT4x is not set\n# CONFIG_SENSORS_SHTC1 is not set\n# CONFIG_SENSORS_SIS5595 is not set\n# CONFIG_SENSORS_DME1737 is not set\n# CONFIG_SENSORS_EMC1403 is not set\n# CONFIG_SENSORS_EMC2103 is not set\n# CONFIG_SENSORS_EMC2305 is not set\n# CONFIG_SENSORS_EMC6W201 is not set\n# CONFIG_SENSORS_SMSC47M1 is not set\n# CONFIG_SENSORS_SMSC47M192 is not set\n# CONFIG_SENSORS_SMSC47B397 is not set\n# CONFIG_SENSORS_SCH5627 is not set\n# CONFIG_SENSORS_SCH5636 is not set\n# CONFIG_SENSORS_STTS751 is not set\n# CONFIG_SENSORS_ADC128D818 is not set\n# CONFIG_SENSORS_ADS7828 is not set\n# CONFIG_SENSORS_AMC6821 is not set\n# CONFIG_SENSORS_INA209 is not set\n# CONFIG_SENSORS_INA2XX is not set\n# CONFIG_SENSORS_INA238 is not set\n# CONFIG_SENSORS_INA3221 is not set\n# CONFIG_SENSORS_SPD5118 is not set\n# CONFIG_SENSORS_TC74 is not set\n# CONFIG_SENSORS_THMC50 is not set\n# CONFIG_SENSORS_TMP102 is not set\n# CONFIG_SENSORS_TMP103 is not set\n# CONFIG_SENSORS_TMP108 is not set\n# CONFIG_SENSORS_TMP401 is not set\n# CONFIG_SENSORS_TMP421 is not set\n# CONFIG_SENSORS_TMP464 is not set\n# CONFIG_SENSORS_TMP513 is not set\n# CONFIG_SENSORS_TSC1641 is not set\n# CONFIG_SENSORS_VIA_CPUTEMP is not set\n# CONFIG_SENSORS_VIA686A is not set\n# CONFIG_SENSORS_VT1211 is not set\n# CONFIG_SENSORS_VT8231 is not set\n# CONFIG_SENSORS_W83773G is not set\n# CONFIG_SENSORS_W83781D is not set\n# CONFIG_SENSORS_W83791D is not set\n# CONFIG_SENSORS_W83792D is not set\n# CONFIG_SENSORS_W83793 is not set\n# CONFIG_SENSORS_W83795 is not set\n# CONFIG_SENSORS_W83L785TS is not set\n# CONFIG_SENSORS_W83L786NG is not set\n# CONFIG_SENSORS_W83627HF is not set\n# CONFIG_SENSORS_W83627EHF is not set\n# CONFIG_SENSORS_XGENE is not set\n\n#\n# ACPI drivers\n#\n# CONFIG_SENSORS_ACPI_POWER is not set\n# CONFIG_SENSORS_ATK0110 is not set\n# CONFIG_SENSORS_ASUS_EC is not set\nCONFIG_THERMAL=y\n# CONFIG_THERMAL_NETLINK is not set\n# CONFIG_THERMAL_STATISTICS is not set\n# CONFIG_THERMAL_DEBUGFS is not set\n# CONFIG_THERMAL_CORE_TESTING is not set\nCONFIG_THERMAL_EMERGENCY_POWEROFF_DELAY_MS=0\nCONFIG_THERMAL_HWMON=y\nCONFIG_THERMAL_DEFAULT_GOV_STEP_WISE=y\n# CONFIG_THERMAL_DEFAULT_GOV_FAIR_SHARE is not set\n# CONFIG_THERMAL_DEFAULT_GOV_USER_SPACE is not set\n# CONFIG_THERMAL_GOV_FAIR_SHARE is not set\nCONFIG_THERMAL_GOV_STEP_WISE=y\n# CONFIG_THERMAL_GOV_BANG_BANG is not set\nCONFIG_THERMAL_GOV_USER_SPACE=y\n# CONFIG_PCIE_THERMAL is not set\n# CONFIG_THERMAL_EMULATION is not set\n\n#\n# Intel thermal drivers\n#\n# CONFIG_INTEL_POWERCLAMP is not set\nCONFIG_X86_THERMAL_VECTOR=y\n# CONFIG_X86_PKG_TEMP_THERMAL is not set\n# CONFIG_INTEL_SOC_DTS_THERMAL is not set\n\n#\n# ACPI INT340X thermal drivers\n#\n# CONFIG_INT340X_THERMAL is not set\n# end of ACPI INT340X thermal drivers\n\n# CONFIG_INTEL_PCH_THERMAL is not set\n# CONFIG_INTEL_TCC_COOLING is not set\n# CONFIG_INTEL_HFI_THERMAL is not set\n# end of Intel thermal drivers\n\nCONFIG_WATCHDOG=y\n# CONFIG_WATCHDOG_CORE is not set\n# CONFIG_WATCHDOG_NOWAYOUT is not set\nCONFIG_WATCHDOG_HANDLE_BOOT_ENABLED=y\nCONFIG_WATCHDOG_OPEN_TIMEOUT=0\n# CONFIG_WATCHDOG_SYSFS is not set\n# CONFIG_WATCHDOG_HRTIMER_PRETIMEOUT is not set\n\n#\n# Watchdog Pretimeout Governors\n#\n\n#\n# Watchdog Device Drivers\n#\n# CONFIG_SOFT_WATCHDOG is not set\n# CONFIG_LENOVO_SE10_WDT is not set\n# CONFIG_LENOVO_SE30_WDT is not set\n# CONFIG_WDAT_WDT is not set\n# CONFIG_XILINX_WATCHDOG is not set\n# CONFIG_ZIIRAVE_WATCHDOG is not set\n# CONFIG_CADENCE_WATCHDOG is not set\n# CONFIG_DW_WATCHDOG is not set\n# CONFIG_MAX63XX_WATCHDOG is not set\n# CONFIG_ACQUIRE_WDT is not set\n# CONFIG_ADVANTECH_WDT is not set\n# CONFIG_ADVANTECH_EC_WDT is not set\n# CONFIG_ALIM1535_WDT is not set\n# CONFIG_ALIM7101_WDT is not set\n# CONFIG_EBC_C384_WDT is not set\n# CONFIG_EXAR_WDT is not set\n# CONFIG_F71808E_WDT is not set\n# CONFIG_SP5100_TCO is not set\n# CONFIG_SBC_FITPC2_WATCHDOG is not set\n# CONFIG_EUROTECH_WDT is not set\n# CONFIG_IB700_WDT is not set\n# CONFIG_IBMASR is not set\n# CONFIG_WAFER_WDT is not set\n# CONFIG_I6300ESB_WDT is not set\n# CONFIG_IE6XX_WDT is not set\n# CONFIG_INTEL_OC_WATCHDOG is not set\n# CONFIG_ITCO_WDT is not set\n# CONFIG_IT8712F_WDT is not set\n# CONFIG_IT87_WDT is not set\n# CONFIG_HP_WATCHDOG is not set\n# CONFIG_SC1200_WDT is not set\n# CONFIG_PC87413_WDT is not set\n# CONFIG_NV_TCO is not set\n# CONFIG_60XX_WDT is not set\n# CONFIG_SMSC_SCH311X_WDT is not set\n# CONFIG_SMSC37B787_WDT is not set\n# CONFIG_TQMX86_WDT is not set\n# CONFIG_VIA_WDT is not set\n# CONFIG_W83627HF_WDT is not set\n# CONFIG_W83877F_WDT is not set\n# CONFIG_W83977F_WDT is not set\n# CONFIG_MACHZ_WDT is not set\n# CONFIG_SBC_EPX_C3_WATCHDOG is not set\n# CONFIG_NI903X_WDT is not set\n# CONFIG_NIC7018_WDT is not set\n\n#\n# PCI-based Watchdog Cards\n#\n# CONFIG_PCIPCWATCHDOG is not set\n# CONFIG_WDTPCI is not set\n\n#\n# USB-based Watchdog Cards\n#\n# CONFIG_USBPCWATCHDOG is not set\nCONFIG_SSB_POSSIBLE=y\n# CONFIG_SSB is not set\nCONFIG_BCMA_POSSIBLE=y\n# CONFIG_BCMA is not set\n\n#\n# Multifunction device drivers\n#\n# CONFIG_MFD_AS3711 is not set\n# CONFIG_MFD_SMPRO is not set\n# CONFIG_PMIC_ADP5520 is not set\n# CONFIG_MFD_BCM590XX is not set\n# CONFIG_MFD_BD9571MWV is not set\n# CONFIG_MFD_AXP20X_I2C is not set\n# CONFIG_MFD_CGBC is not set\n# CONFIG_MFD_CS40L50_I2C is not set\n# CONFIG_MFD_CS42L43_I2C is not set\n# CONFIG_MFD_MADERA is not set\n# CONFIG_PMIC_DA903X is not set\n# CONFIG_MFD_DA9052_I2C is not set\n# CONFIG_MFD_DA9055 is not set\n# CONFIG_MFD_DA9062 is not set\n# CONFIG_MFD_DA9063 is not set\n# CONFIG_MFD_DA9150 is not set\n# CONFIG_MFD_DLN2 is not set\n# CONFIG_MFD_MC13XXX_I2C is not set\n# CONFIG_MFD_MP2629 is not set\n# CONFIG_MFD_INTEL_QUARK_I2C_GPIO is not set\n# CONFIG_LPC_ICH is not set\n# CONFIG_LPC_SCH is not set\n# CONFIG_MFD_INTEL_LPSS_ACPI is not set\n# CONFIG_MFD_INTEL_LPSS_PCI is not set\n# CONFIG_MFD_INTEL_PMC_BXT is not set\n# CONFIG_MFD_IQS62X is not set\n# CONFIG_MFD_JANZ_CMODIO is not set\n# CONFIG_MFD_KEMPLD is not set\n# CONFIG_MFD_88PM800 is not set\n# CONFIG_MFD_88PM805 is not set\n# CONFIG_MFD_88PM860X is not set\n# CONFIG_MFD_MAX5970 is not set\n# CONFIG_MFD_MAX14577 is not set\n# CONFIG_MFD_MAX77541 is not set\n# CONFIG_MFD_MAX77693 is not set\n# CONFIG_MFD_MAX77705 is not set\n# CONFIG_MFD_MAX77843 is not set\n# CONFIG_MFD_MAX8907 is not set\n# CONFIG_MFD_MAX8925 is not set\n# CONFIG_MFD_MAX8997 is not set\n# CONFIG_MFD_MAX8998 is not set\n# CONFIG_MFD_MT6360 is not set\n# CONFIG_MFD_MT6370 is not set\n# CONFIG_MFD_MT6397 is not set\n# CONFIG_MFD_MENF21BMC is not set\n# CONFIG_MFD_NCT6694 is not set\n# CONFIG_MFD_VIPERBOARD is not set\n# CONFIG_MFD_RETU is not set\n# CONFIG_MFD_SY7636A is not set\n# CONFIG_MFD_RDC321X is not set\n# CONFIG_MFD_RT4831 is not set\n# CONFIG_MFD_RT5033 is not set\n# CONFIG_MFD_RT5120 is not set\n# CONFIG_MFD_RC5T583 is not set\n# CONFIG_MFD_SI476X_CORE is not set\n# CONFIG_MFD_SM501 is not set\n# CONFIG_MFD_SKY81452 is not set\n# CONFIG_MFD_SYSCON is not set\n# CONFIG_MFD_LP3943 is not set\n# CONFIG_MFD_LP8788 is not set\n# CONFIG_MFD_TI_LMU is not set\n# CONFIG_MFD_BQ257XX is not set\n# CONFIG_MFD_PALMAS is not set\n# CONFIG_TPS6105X is not set\n# CONFIG_TPS6507X is not set\n# CONFIG_MFD_TPS65086 is not set\n# CONFIG_MFD_TPS65090 is not set\n# CONFIG_MFD_TI_LP873X is not set\n# CONFIG_MFD_TPS6586X is not set\n# CONFIG_MFD_TPS65912_I2C is not set\n# CONFIG_MFD_TPS6594_I2C is not set\n# CONFIG_TWL4030_CORE is not set\n# CONFIG_TWL6040_CORE is not set\n# CONFIG_MFD_LM3533 is not set\n# CONFIG_MFD_TQMX86 is not set\n# CONFIG_MFD_VX855 is not set\n# CONFIG_MFD_ARIZONA_I2C is not set\n# CONFIG_MFD_WM8400 is not set\n# CONFIG_MFD_WM831X_I2C is not set\n# CONFIG_MFD_WM8350_I2C is not set\n# CONFIG_MFD_WM8994 is not set\n# CONFIG_MFD_ATC260X_I2C is not set\n# CONFIG_MFD_UPBOARD_FPGA is not set\n# CONFIG_MFD_MAX7360 is not set\n# end of Multifunction device drivers\n\n# CONFIG_REGULATOR is not set\n# CONFIG_RC_CORE is not set\n\n#\n# CEC support\n#\n# CONFIG_MEDIA_CEC_SUPPORT is not set\n# end of CEC support\n\n# CONFIG_MEDIA_SUPPORT is not set\n\n#\n# Graphics support\n#\nCONFIG_APERTURE_HELPERS=y\nCONFIG_SCREEN_INFO=y\nCONFIG_VIDEO=y\n# CONFIG_AUXDISPLAY is not set\nCONFIG_AGP=y\nCONFIG_AGP_AMD64=y\nCONFIG_AGP_INTEL=y\n# CONFIG_AGP_SIS is not set\n# CONFIG_AGP_VIA is not set\nCONFIG_INTEL_GTT=y\n# CONFIG_VGA_SWITCHEROO is not set\nCONFIG_DRM=y\n\n#\n# DRM debugging options\n#\n# CONFIG_DRM_WERROR is not set\n# CONFIG_DRM_DEBUG_MM is not set\n# end of DRM debugging options\n\n# CONFIG_DRM_PANIC is not set\n# CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS is not set\n# CONFIG_DRM_DEBUG_MODESET_LOCK is not set\n# CONFIG_DRM_LOAD_EDID_FIRMWARE is not set\n\n#\n# Drivers for system framebuffers\n#\n# CONFIG_DRM_EFIDRM is not set\n# CONFIG_DRM_SIMPLEDRM is not set\n# CONFIG_DRM_VESADRM is not set\n# end of Drivers for system framebuffers\n\n#\n# ARM devices\n#\n# end of ARM devices\n\n# CONFIG_DRM_RADEON is not set\n# CONFIG_DRM_AMDGPU is not set\n# CONFIG_DRM_NOUVEAU is not set\n# CONFIG_DRM_I915 is not set\n# CONFIG_DRM_XE is not set\n# CONFIG_DRM_VGEM is not set\n# CONFIG_DRM_VKMS is not set\n# CONFIG_DRM_VMWGFX is not set\n# CONFIG_DRM_GMA500 is not set\n# CONFIG_DRM_UDL is not set\n# CONFIG_DRM_AST is not set\n# CONFIG_DRM_MGAG200 is not set\n# CONFIG_DRM_QXL is not set\n# CONFIG_DRM_VIRTIO_GPU is not set\nCONFIG_DRM_PANEL=y\n\n#\n# Display Panels\n#\n# end of Display Panels\n\nCONFIG_DRM_BRIDGE=y\nCONFIG_DRM_PANEL_BRIDGE=y\n\n#\n# Display Interface Bridges\n#\n# CONFIG_DRM_I2C_NXP_TDA998X is not set\n# CONFIG_DRM_ANALOGIX_ANX78XX is not set\n# end of Display Interface Bridges\n\n# CONFIG_DRM_ETNAVIV is not set\n# CONFIG_DRM_HISI_HIBMC is not set\n# CONFIG_DRM_APPLETBDRM is not set\n# CONFIG_DRM_BOCHS is not set\n# CONFIG_DRM_CIRRUS_QEMU is not set\n# CONFIG_DRM_GM12U320 is not set\n# CONFIG_DRM_VBOXVIDEO is not set\n# CONFIG_DRM_GUD is not set\n# CONFIG_DRM_ST7571_I2C is not set\n# CONFIG_DRM_SSD130X is not set\nCONFIG_DRM_PANEL_ORIENTATION_QUIRKS=y\n\n#\n# Frame buffer Devices\n#\nCONFIG_FB=y\n# CONFIG_FB_CIRRUS is not set\n# CONFIG_FB_PM2 is not set\n# CONFIG_FB_CYBER2000 is not set\n# CONFIG_FB_ARC is not set\n# CONFIG_FB_ASILIANT is not set\n# CONFIG_FB_IMSTT is not set\n# CONFIG_FB_VGA16 is not set\n# CONFIG_FB_UVESA is not set\n# CONFIG_FB_VESA is not set\nCONFIG_FB_EFI=y\n# CONFIG_FB_N411 is not set\n# CONFIG_FB_HGA is not set\n# CONFIG_FB_OPENCORES is not set\n# CONFIG_FB_S1D13XXX is not set\n# CONFIG_FB_NVIDIA is not set\n# CONFIG_FB_RIVA is not set\n# CONFIG_FB_I740 is not set\n# CONFIG_FB_MATROX is not set\n# CONFIG_FB_RADEON is not set\n# CONFIG_FB_ATY128 is not set\n# CONFIG_FB_ATY is not set\n# CONFIG_FB_S3 is not set\n# CONFIG_FB_SAVAGE is not set\n# CONFIG_FB_SIS is not set\n# CONFIG_FB_NEOMAGIC is not set\n# CONFIG_FB_KYRO is not set\n# CONFIG_FB_3DFX is not set\n# CONFIG_FB_VOODOO1 is not set\n# CONFIG_FB_VT8623 is not set\n# CONFIG_FB_TRIDENT is not set\n# CONFIG_FB_ARK is not set\n# CONFIG_FB_PM3 is not set\n# CONFIG_FB_CARMINE is not set\n# CONFIG_FB_SMSCUFX is not set\n# CONFIG_FB_UDL is not set\n# CONFIG_FB_IBM_GXT4500 is not set\n# CONFIG_FB_VIRTUAL is not set\n# CONFIG_FB_METRONOME is not set\n# CONFIG_FB_MB862XX is not set\n# CONFIG_FB_SIMPLE is not set\n# CONFIG_FB_SM712 is not set\nCONFIG_FB_CORE=y\nCONFIG_FB_NOTIFY=y\nCONFIG_FB_DEVICE=y\nCONFIG_FB_CFB_FILLRECT=y\nCONFIG_FB_CFB_COPYAREA=y\nCONFIG_FB_CFB_IMAGEBLIT=y\n# CONFIG_FB_FOREIGN_ENDIAN is not set\nCONFIG_FB_IOMEM_FOPS=y\nCONFIG_FB_IOMEM_HELPERS=y\nCONFIG_FB_TILEBLITTING=y\n# end of Frame buffer Devices\n\n#\n# Backlight & LCD device support\n#\n# CONFIG_LCD_CLASS_DEVICE is not set\nCONFIG_BACKLIGHT_CLASS_DEVICE=y\n# CONFIG_BACKLIGHT_AW99706 is not set\n# CONFIG_BACKLIGHT_KTZ8866 is not set\n# CONFIG_BACKLIGHT_APPLE is not set\n# CONFIG_BACKLIGHT_QCOM_WLED is not set\n# CONFIG_BACKLIGHT_SAHARA is not set\n# CONFIG_BACKLIGHT_ADP8860 is not set\n# CONFIG_BACKLIGHT_ADP8870 is not set\n# CONFIG_BACKLIGHT_LM3509 is not set\n# CONFIG_BACKLIGHT_LM3639 is not set\n# CONFIG_BACKLIGHT_LV5207LP is not set\n# CONFIG_BACKLIGHT_BD6107 is not set\n# CONFIG_BACKLIGHT_ARCXCNN is not set\n# end of Backlight & LCD device support\n\nCONFIG_HDMI=y\n# CONFIG_FIRMWARE_EDID is not set\n\n#\n# Console display driver support\n#\nCONFIG_VGA_CONSOLE=y\nCONFIG_DUMMY_CONSOLE=y\nCONFIG_DUMMY_CONSOLE_COLUMNS=80\nCONFIG_DUMMY_CONSOLE_ROWS=25\nCONFIG_FRAMEBUFFER_CONSOLE=y\n# CONFIG_FRAMEBUFFER_CONSOLE_LEGACY_ACCELERATION is not set\nCONFIG_FRAMEBUFFER_CONSOLE_DETECT_PRIMARY=y\n# CONFIG_FRAMEBUFFER_CONSOLE_ROTATION is not set\nCONFIG_FRAMEBUFFER_CONSOLE_DEFERRED_TAKEOVER=y\n# end of Console display driver support\n\nCONFIG_LOGO=y\n# CONFIG_LOGO_LINUX_MONO is not set\n# CONFIG_LOGO_LINUX_VGA16 is not set\nCONFIG_LOGO_LINUX_CLUT224=y\n# CONFIG_TRACE_GPU_MEM is not set\n# end of Graphics support\n\n# CONFIG_DRM_ACCEL is not set\n# CONFIG_SOUND is not set\nCONFIG_HID_SUPPORT=y\nCONFIG_HID=y\nCONFIG_HID_BATTERY_STRENGTH=y\nCONFIG_HIDRAW=y\n# CONFIG_UHID is not set\nCONFIG_HID_GENERIC=y\n# CONFIG_HID_HAPTIC is not set\n\n#\n# Special HID drivers\n#\n# CONFIG_HID_A4TECH is not set\n# CONFIG_HID_ACCUTOUCH is not set\n# CONFIG_HID_ACRUX is not set\n# CONFIG_HID_APPLEIR is not set\n# CONFIG_HID_APPLETB_BL is not set\n# CONFIG_HID_APPLETB_KBD is not set\n# CONFIG_HID_AUREAL is not set\n# CONFIG_HID_BELKIN is not set\n# CONFIG_HID_BETOP_FF is not set\n# CONFIG_HID_CHERRY is not set\n# CONFIG_HID_CHICONY is not set\n# CONFIG_HID_COUGAR is not set\n# CONFIG_HID_MACALLY is not set\n# CONFIG_HID_CMEDIA is not set\n# CONFIG_HID_CREATIVE_SB0540 is not set\n# CONFIG_HID_CYPRESS is not set\n# CONFIG_HID_DRAGONRISE is not set\n# CONFIG_HID_EMS_FF is not set\n# CONFIG_HID_ELECOM is not set\n# CONFIG_HID_ELO is not set\n# CONFIG_HID_EVISION is not set\n# CONFIG_HID_EZKEY is not set\n# CONFIG_HID_FT260 is not set\n# CONFIG_HID_GEMBIRD is not set\n# CONFIG_HID_GFRM is not set\n# CONFIG_HID_GLORIOUS is not set\n# CONFIG_HID_HOLTEK is not set\n# CONFIG_HID_GOOGLE_STADIA_FF is not set\n# CONFIG_HID_VIVALDI is not set\n# CONFIG_HID_KEYTOUCH is not set\n# CONFIG_HID_KYE is not set\n# CONFIG_HID_KYSONA is not set\n# CONFIG_HID_UCLOGIC is not set\n# CONFIG_HID_WALTOP is not set\n# CONFIG_HID_VIEWSONIC is not set\n# CONFIG_HID_VRC2 is not set\n# CONFIG_HID_XIAOMI is not set\nCONFIG_HID_GYRATION=y\n# CONFIG_HID_ICADE is not set\n# CONFIG_HID_ITE is not set\n# CONFIG_HID_JABRA is not set\n# CONFIG_HID_TWINHAN is not set\n# CONFIG_HID_KENSINGTON is not set\n# CONFIG_HID_LCPOWER is not set\n# CONFIG_HID_LENOVO is not set\n# CONFIG_HID_LETSKETCH is not set\n# CONFIG_HID_MAGICMOUSE is not set\n# CONFIG_HID_MALTRON is not set\n# CONFIG_HID_MAYFLASH is not set\n# CONFIG_HID_MEGAWORLD_FF is not set\n# CONFIG_HID_REDRAGON is not set\n# CONFIG_HID_MICROSOFT is not set\n# CONFIG_HID_MONTEREY is not set\n# CONFIG_HID_MULTITOUCH is not set\n# CONFIG_HID_NTI is not set\nCONFIG_HID_NTRIG=y\n# CONFIG_HID_ORTEK is not set\nCONFIG_HID_PANTHERLORD=y\nCONFIG_PANTHERLORD_FF=y\n# CONFIG_HID_PENMOUNT is not set\nCONFIG_HID_PETALYNX=y\n# CONFIG_HID_PICOLCD is not set\n# CONFIG_HID_PLANTRONICS is not set\n# CONFIG_HID_PXRC is not set\n# CONFIG_HID_RAZER is not set\n# CONFIG_HID_PRIMAX is not set\n# CONFIG_HID_RETRODE is not set\n# CONFIG_HID_ROCCAT is not set\n# CONFIG_HID_SAITEK is not set\nCONFIG_HID_SAMSUNG=y\n# CONFIG_HID_SEMITEK is not set\n# CONFIG_HID_SIGMAMICRO is not set\n# CONFIG_HID_SPEEDLINK is not set\n# CONFIG_HID_STEAM is not set\n# CONFIG_HID_STEELSERIES is not set\nCONFIG_HID_SUNPLUS=y\n# CONFIG_HID_RMI is not set\n# CONFIG_HID_GREENASIA is not set\n# CONFIG_HID_SMARTJOYPLUS is not set\n# CONFIG_HID_TIVO is not set\nCONFIG_HID_TOPSEED=y\n# CONFIG_HID_TOPRE is not set\n# CONFIG_HID_THRUSTMASTER is not set\n# CONFIG_HID_UDRAW_PS3 is not set\n# CONFIG_HID_UNIVERSAL_PIDFF is not set\n# CONFIG_HID_WACOM is not set\n# CONFIG_HID_XINMO is not set\n# CONFIG_HID_ZEROPLUS is not set\n# CONFIG_HID_ZYDACRON is not set\n# CONFIG_HID_SENSOR_HUB is not set\n# CONFIG_HID_ALPS is not set\n# CONFIG_HID_MCP2221 is not set\n# end of Special HID drivers\n\n#\n# HID-BPF support\n#\nCONFIG_HID_BPF=y\n# end of HID-BPF support\n\nCONFIG_I2C_HID=y\n# CONFIG_I2C_HID_ACPI is not set\n# CONFIG_I2C_HID_OF is not set\n\n#\n# Intel ISH HID support\n#\n# CONFIG_INTEL_ISH_HID is not set\n# end of Intel ISH HID support\n\n#\n# AMD SFH HID Support\n#\n# CONFIG_AMD_SFH_HID is not set\n# end of AMD SFH HID Support\n\n#\n# Intel THC HID Support\n#\n# CONFIG_INTEL_THC_HID is not set\n# end of Intel THC HID Support\n\n#\n# USB HID support\n#\nCONFIG_USB_HID=y\nCONFIG_HID_PID=y\nCONFIG_USB_HIDDEV=y\n# end of USB HID support\n\nCONFIG_USB_OHCI_LITTLE_ENDIAN=y\nCONFIG_USB_SUPPORT=y\nCONFIG_USB_COMMON=y\n# CONFIG_USB_ULPI_BUS is not set\nCONFIG_USB_ARCH_HAS_HCD=y\nCONFIG_USB=y\nCONFIG_USB_PCI=y\nCONFIG_USB_PCI_AMD=y\nCONFIG_USB_ANNOUNCE_NEW_DEVICES=y\n\n#\n# Miscellaneous USB options\n#\nCONFIG_USB_DEFAULT_PERSIST=y\n# CONFIG_USB_FEW_INIT_RETRIES is not set\n# CONFIG_USB_DYNAMIC_MINORS is not set\n# CONFIG_USB_OTG is not set\n# CONFIG_USB_OTG_PRODUCTLIST is not set\n# CONFIG_USB_OTG_DISABLE_EXTERNAL_HUB is not set\nCONFIG_USB_AUTOSUSPEND_DELAY=2\nCONFIG_USB_DEFAULT_AUTHORIZATION_MODE=1\nCONFIG_USB_MON=y\n\n#\n# USB Host Controller Drivers\n#\n# CONFIG_USB_C67X00_HCD is not set\n# CONFIG_USB_XHCI_HCD is not set\n# CONFIG_USB_EHCI_HCD is not set\n# CONFIG_USB_OXU210HP_HCD is not set\n# CONFIG_USB_ISP116X_HCD is not set\nCONFIG_USB_OHCI_HCD=y\nCONFIG_USB_OHCI_HCD_PCI=y\n# CONFIG_USB_OHCI_HCD_PLATFORM is not set\nCONFIG_USB_UHCI_HCD=y\n# CONFIG_USB_SL811_HCD is not set\n# CONFIG_USB_R8A66597_HCD is not set\n# CONFIG_USB_HCD_TEST_MODE is not set\n\n#\n# USB Device Class drivers\n#\n# CONFIG_USB_ACM is not set\nCONFIG_USB_PRINTER=y\n# CONFIG_USB_WDM is not set\n# CONFIG_USB_TMC is not set\n\n#\n# NOTE: USB_STORAGE depends on SCSI but BLK_DEV_SD may also be needed; see USB_STORAGE Help for more info\n#\nCONFIG_USB_STORAGE=y\n# CONFIG_USB_STORAGE_DEBUG is not set\n# CONFIG_USB_STORAGE_REALTEK is not set\n# CONFIG_USB_STORAGE_DATAFAB is not set\n# CONFIG_USB_STORAGE_FREECOM is not set\n# CONFIG_USB_STORAGE_ISD200 is not set\n# CONFIG_USB_STORAGE_USBAT is not set\n# CONFIG_USB_STORAGE_SDDR09 is not set\n# CONFIG_USB_STORAGE_SDDR55 is not set\n# CONFIG_USB_STORAGE_JUMPSHOT is not set\n# CONFIG_USB_STORAGE_ALAUDA is not set\n# CONFIG_USB_STORAGE_ONETOUCH is not set\n# CONFIG_USB_STORAGE_KARMA is not set\n# CONFIG_USB_STORAGE_CYPRESS_ATACB is not set\n# CONFIG_USB_STORAGE_ENE_UB6250 is not set\n# CONFIG_USB_UAS is not set\n\n#\n# USB Imaging devices\n#\n# CONFIG_USB_MDC800 is not set\n# CONFIG_USB_MICROTEK is not set\n# CONFIG_USBIP_CORE is not set\n\n#\n# USB dual-mode controller drivers\n#\n# CONFIG_USB_CDNS_SUPPORT is not set\n# CONFIG_USB_MUSB_HDRC is not set\n# CONFIG_USB_DWC3 is not set\n# CONFIG_USB_DWC2 is not set\n# CONFIG_USB_ISP1760 is not set\n\n#\n# USB port drivers\n#\n# CONFIG_USB_SERIAL is not set\n\n#\n# USB Miscellaneous drivers\n#\n# CONFIG_USB_EMI62 is not set\n# CONFIG_USB_EMI26 is not set\n# CONFIG_USB_ADUTUX is not set\n# CONFIG_USB_SEVSEG is not set\n# CONFIG_USB_LEGOTOWER is not set\n# CONFIG_USB_LCD is not set\n# CONFIG_USB_CYPRESS_CY7C63 is not set\n# CONFIG_USB_CYTHERM is not set\n# CONFIG_USB_IDMOUSE is not set\n# CONFIG_USB_APPLEDISPLAY is not set\n# CONFIG_APPLE_MFI_FASTCHARGE is not set\n# CONFIG_USB_LJCA is not set\n# CONFIG_USB_USBIO is not set\n# CONFIG_USB_LD is not set\n# CONFIG_USB_TRANCEVIBRATOR is not set\n# CONFIG_USB_IOWARRIOR is not set\n# CONFIG_USB_TEST is not set\n# CONFIG_USB_EHSET_TEST_FIXTURE is not set\n# CONFIG_USB_ISIGHTFW is not set\n# CONFIG_USB_YUREX is not set\n# CONFIG_USB_EZUSB_FX2 is not set\n# CONFIG_USB_HUB_USB251XB is not set\n# CONFIG_USB_HSIC_USB3503 is not set\n# CONFIG_USB_HSIC_USB4604 is not set\n# CONFIG_USB_LINK_LAYER_TEST is not set\n# CONFIG_USB_CHAOSKEY is not set\n\n#\n# USB Physical Layer drivers\n#\n# CONFIG_NOP_USB_XCEIV is not set\n# CONFIG_USB_ISP1301 is not set\n# end of USB Physical Layer drivers\n\n# CONFIG_USB_GADGET is not set\n# CONFIG_TYPEC is not set\n# CONFIG_USB_ROLE_SWITCH is not set\n# CONFIG_MMC is not set\n# CONFIG_SCSI_UFSHCD is not set\n# CONFIG_MEMSTICK is not set\n# CONFIG_NEW_LEDS is not set\n# CONFIG_ACCESSIBILITY is not set\n# CONFIG_INFINIBAND is not set\nCONFIG_EDAC_ATOMIC_SCRUB=y\nCONFIG_EDAC_SUPPORT=y\nCONFIG_EDAC=y\n# CONFIG_EDAC_DEBUG is not set\nCONFIG_EDAC_DECODE_MCE=y\n# CONFIG_EDAC_SCRUB is not set\n# CONFIG_EDAC_ECS is not set\n# CONFIG_EDAC_MEM_REPAIR is not set\n# CONFIG_EDAC_AMD64 is not set\n# CONFIG_EDAC_E752X is not set\n# CONFIG_EDAC_I82975X is not set\n# CONFIG_EDAC_I3000 is not set\n# CONFIG_EDAC_I3200 is not set\n# CONFIG_EDAC_IE31200 is not set\n# CONFIG_EDAC_X38 is not set\n# CONFIG_EDAC_I5400 is not set\n# CONFIG_EDAC_I7CORE is not set\n# CONFIG_EDAC_I5100 is not set\n# CONFIG_EDAC_I7300 is not set\n# CONFIG_EDAC_SBRIDGE is not set\n# CONFIG_EDAC_SKX is not set\n# CONFIG_EDAC_I10NM is not set\n# CONFIG_EDAC_IMH is not set\n# CONFIG_EDAC_PND2 is not set\n# CONFIG_EDAC_IGEN6 is not set\nCONFIG_RTC_LIB=y\nCONFIG_RTC_MC146818_LIB=y\nCONFIG_RTC_CLASS=y\n# CONFIG_RTC_HCTOSYS is not set\nCONFIG_RTC_SYSTOHC=y\nCONFIG_RTC_SYSTOHC_DEVICE=\"rtc0\"\n# CONFIG_RTC_DEBUG is not set\nCONFIG_RTC_NVMEM=y\n\n#\n# RTC interfaces\n#\nCONFIG_RTC_INTF_SYSFS=y\nCONFIG_RTC_INTF_PROC=y\nCONFIG_RTC_INTF_DEV=y\n# CONFIG_RTC_INTF_DEV_UIE_EMUL is not set\n# CONFIG_RTC_DRV_TEST is not set\n\n#\n# I2C RTC drivers\n#\n# CONFIG_RTC_DRV_ABB5ZES3 is not set\n# CONFIG_RTC_DRV_ABEOZ9 is not set\n# CONFIG_RTC_DRV_ABX80X is not set\n# CONFIG_RTC_DRV_DS1307 is not set\n# CONFIG_RTC_DRV_DS1374 is not set\n# CONFIG_RTC_DRV_DS1672 is not set\n# CONFIG_RTC_DRV_MAX6900 is not set\n# CONFIG_RTC_DRV_MAX31335 is not set\n# CONFIG_RTC_DRV_NVIDIA_VRS10 is not set\n# CONFIG_RTC_DRV_RS5C372 is not set\n# CONFIG_RTC_DRV_ISL1208 is not set\n# CONFIG_RTC_DRV_ISL12022 is not set\n# CONFIG_RTC_DRV_X1205 is not set\n# CONFIG_RTC_DRV_PCF8523 is not set\n# CONFIG_RTC_DRV_PCF85363 is not set\n# CONFIG_RTC_DRV_PCF8563 is not set\n# CONFIG_RTC_DRV_PCF8583 is not set\n# CONFIG_RTC_DRV_M41T80 is not set\n# CONFIG_RTC_DRV_BQ32K is not set\n# CONFIG_RTC_DRV_S35390A is not set\n# CONFIG_RTC_DRV_FM3130 is not set\n# CONFIG_RTC_DRV_RX8010 is not set\n# CONFIG_RTC_DRV_RX8111 is not set\n# CONFIG_RTC_DRV_RX8581 is not set\n# CONFIG_RTC_DRV_RX8025 is not set\n# CONFIG_RTC_DRV_EM3027 is not set\n# CONFIG_RTC_DRV_RV3028 is not set\n# CONFIG_RTC_DRV_RV3032 is not set\n# CONFIG_RTC_DRV_RV8803 is not set\n# CONFIG_RTC_DRV_SD2405AL is not set\n# CONFIG_RTC_DRV_SD3078 is not set\n\n#\n# SPI RTC drivers\n#\nCONFIG_RTC_I2C_AND_SPI=y\n\n#\n# SPI and I2C RTC drivers\n#\n# CONFIG_RTC_DRV_DS3232 is not set\n# CONFIG_RTC_DRV_PCF2127 is not set\n# CONFIG_RTC_DRV_PCF85063 is not set\n# CONFIG_RTC_DRV_RV3029C2 is not set\n# CONFIG_RTC_DRV_RX6110 is not set\n\n#\n# Platform RTC drivers\n#\nCONFIG_RTC_DRV_CMOS=y\n# CONFIG_RTC_DRV_DS1286 is not set\n# CONFIG_RTC_DRV_DS1511 is not set\n# CONFIG_RTC_DRV_DS1553 is not set\n# CONFIG_RTC_DRV_DS1685_FAMILY is not set\n# CONFIG_RTC_DRV_DS1742 is not set\n# CONFIG_RTC_DRV_DS2404 is not set\n# CONFIG_RTC_DRV_STK17TA8 is not set\n# CONFIG_RTC_DRV_M48T86 is not set\n# CONFIG_RTC_DRV_M48T35 is not set\n# CONFIG_RTC_DRV_M48T59 is not set\n# CONFIG_RTC_DRV_MSM6242 is not set\n# CONFIG_RTC_DRV_RP5C01 is not set\n\n#\n# on-CPU RTC drivers\n#\n# CONFIG_RTC_DRV_FTRTC010 is not set\n# CONFIG_RTC_DRV_GOLDFISH is not set\n\n#\n# HID Sensor RTC drivers\n#\nCONFIG_DMADEVICES=y\n# CONFIG_DMADEVICES_DEBUG is not set\n\n#\n# DMA Devices\n#\nCONFIG_DMA_ENGINE=y\nCONFIG_DMA_VIRTUAL_CHANNELS=y\nCONFIG_DMA_ACPI=y\n# CONFIG_ALTERA_MSGDMA is not set\n# CONFIG_INTEL_IDMA64 is not set\n# CONFIG_INTEL_IDXD is not set\n# CONFIG_INTEL_IDXD_COMPAT is not set\n# CONFIG_INTEL_IOATDMA is not set\n# CONFIG_PLX_DMA is not set\n# CONFIG_XILINX_DMA is not set\n# CONFIG_XILINX_XDMA is not set\n# CONFIG_AMD_PTDMA is not set\n# CONFIG_AMD_QDMA is not set\n# CONFIG_QCOM_HIDMA_MGMT is not set\n# CONFIG_QCOM_HIDMA is not set\nCONFIG_DW_DMAC_CORE=y\n# CONFIG_DW_DMAC is not set\nCONFIG_DW_DMAC_PCI=y\n# CONFIG_DW_EDMA is not set\nCONFIG_HSU_DMA=y\n# CONFIG_SF_PDMA is not set\n# CONFIG_INTEL_LDMA is not set\n\n#\n# DMA Clients\n#\n# CONFIG_ASYNC_TX_DMA is not set\n# CONFIG_DMATEST is not set\n\n#\n# DMABUF options\n#\nCONFIG_SYNC_FILE=y\n# CONFIG_SW_SYNC is not set\n# CONFIG_UDMABUF is not set\n# CONFIG_DMABUF_MOVE_NOTIFY is not set\n# CONFIG_DMABUF_DEBUG is not set\n# CONFIG_DMABUF_SELFTESTS is not set\n# CONFIG_DMABUF_HEAPS is not set\n# CONFIG_DMABUF_SYSFS_STATS is not set\n# end of DMABUF options\n\n# CONFIG_UIO is not set\n# CONFIG_VFIO is not set\n# CONFIG_VIRT_DRIVERS is not set\nCONFIG_VIRTIO_ANCHOR=y\nCONFIG_VIRTIO=y\nCONFIG_VIRTIO_PCI_LIB=y\nCONFIG_VIRTIO_PCI_LIB_LEGACY=y\nCONFIG_VIRTIO_MENU=y\nCONFIG_VIRTIO_PCI=y\nCONFIG_VIRTIO_PCI_ADMIN_LEGACY=y\nCONFIG_VIRTIO_PCI_LEGACY=y\n# CONFIG_VIRTIO_BALLOON is not set\n# CONFIG_VIRTIO_INPUT is not set\n# CONFIG_VIRTIO_MMIO is not set\n# CONFIG_VIRTIO_DEBUG is not set\n# CONFIG_VIRTIO_RTC is not set\n# CONFIG_VDPA is not set\nCONFIG_VHOST_IOTLB=y\nCONFIG_VHOST_TASK=y\nCONFIG_VHOST=y\nCONFIG_VHOST_MENU=y\nCONFIG_VHOST_NET=y\n# CONFIG_VHOST_CROSS_ENDIAN_LEGACY is not set\nCONFIG_VHOST_ENABLE_FORK_OWNER_CONTROL=y\n\n#\n# Microsoft Hyper-V guest support\n#\n# CONFIG_HYPERV is not set\n# end of Microsoft Hyper-V guest support\n\n# CONFIG_GREYBUS is not set\n# CONFIG_COMEDI is not set\n# CONFIG_GPIB is not set\n# CONFIG_STAGING is not set\n# CONFIG_GOLDFISH is not set\n# CONFIG_CHROME_PLATFORMS is not set\n# CONFIG_MELLANOX_PLATFORM is not set\n# CONFIG_SURFACE_PLATFORMS is not set\nCONFIG_X86_PLATFORM_DEVICES=y\n# CONFIG_X86_PLATFORM_DRIVERS_UNIWILL is not set\n# CONFIG_ACERHDF is not set\n# CONFIG_ACER_WIRELESS is not set\n\n#\n# AMD HSMP Driver\n#\n# CONFIG_AMD_HSMP_ACPI is not set\n# CONFIG_AMD_HSMP_PLAT is not set\n# end of AMD HSMP Driver\n\n# CONFIG_AMD_PMC is not set\n# CONFIG_AMD_HFI is not set\n# CONFIG_AMD_3D_VCACHE is not set\n# CONFIG_AMD_WBRF is not set\n# CONFIG_AMD_ISP_PLATFORM is not set\n# CONFIG_ADV_SWBUTTON is not set\n# CONFIG_APPLE_GMUX is not set\n# CONFIG_ASUS_LAPTOP is not set\n# CONFIG_ASUS_WIRELESS is not set\n# CONFIG_AYANEO_EC is not set\n# CONFIG_EEEPC_LAPTOP is not set\n# CONFIG_X86_PLATFORM_DRIVERS_DELL is not set\n# CONFIG_AMILO_RFKILL is not set\n# CONFIG_FUJITSU_LAPTOP is not set\n# CONFIG_FUJITSU_TABLET is not set\n# CONFIG_GPD_POCKET_FAN is not set\n# CONFIG_X86_PLATFORM_DRIVERS_HP is not set\n# CONFIG_WIRELESS_HOTKEY is not set\n# CONFIG_IBM_RTL is not set\n# CONFIG_SENSORS_HDAPS is not set\n# CONFIG_INTEL_ATOMISP2_PM is not set\n# CONFIG_INTEL_IFS is not set\n# CONFIG_INTEL_SAR_INT1092 is not set\n\n#\n# Intel Speed Select Technology interface support\n#\n# CONFIG_INTEL_SPEED_SELECT_INTERFACE is not set\n# end of Intel Speed Select Technology interface support\n\n#\n# Intel Uncore Frequency Control\n#\n# CONFIG_INTEL_UNCORE_FREQ_CONTROL is not set\n# end of Intel Uncore Frequency Control\n\n# CONFIG_INTEL_HID_EVENT is not set\n# CONFIG_INTEL_VBTN is not set\n# CONFIG_INTEL_EHL_PSE_IO is not set\n# CONFIG_INTEL_OAKTRAIL is not set\n# CONFIG_INTEL_PUNIT_IPC is not set\n# CONFIG_INTEL_RST is not set\n# CONFIG_INTEL_SMARTCONNECT is not set\n# CONFIG_INTEL_TURBO_MAX_3 is not set\n# CONFIG_INTEL_VSEC is not set\n# CONFIG_IDEAPAD_LAPTOP is not set\n# CONFIG_THINKPAD_ACPI is not set\n# CONFIG_ACPI_QUICKSTART is not set\n# CONFIG_MSI_EC is not set\n# CONFIG_MSI_LAPTOP is not set\n# CONFIG_SAMSUNG_LAPTOP is not set\n# CONFIG_SAMSUNG_Q10 is not set\n# CONFIG_TOSHIBA_BT_RFKILL is not set\n# CONFIG_TOSHIBA_HAPS is not set\n# CONFIG_ACPI_CMPC is not set\n# CONFIG_COMPAL_LAPTOP is not set\n# CONFIG_PANASONIC_LAPTOP is not set\n# CONFIG_SONY_LAPTOP is not set\n# CONFIG_SYSTEM76_ACPI is not set\n# CONFIG_TOPSTAR_LAPTOP is not set\n# CONFIG_SERIAL_MULTI_INSTANTIATE is not set\n# CONFIG_DASHARO_ACPI is not set\n# CONFIG_INTEL_IPS is not set\n# CONFIG_INTEL_SCU_PCI is not set\n# CONFIG_INTEL_SCU_PLATFORM is not set\n# CONFIG_SIEMENS_SIMATIC_IPC is not set\n# CONFIG_WINMATE_FM07_KEYS is not set\n# CONFIG_OXP_EC is not set\nCONFIG_P2SB=y\n# CONFIG_ACPI_WMI is not set\nCONFIG_HAVE_CLK=y\nCONFIG_HAVE_CLK_PREPARE=y\nCONFIG_COMMON_CLK=y\n# CONFIG_COMMON_CLK_MAX9485 is not set\n# CONFIG_COMMON_CLK_SI5341 is not set\n# CONFIG_COMMON_CLK_SI5351 is not set\n# CONFIG_COMMON_CLK_SI544 is not set\n# CONFIG_COMMON_CLK_CDCE706 is not set\n# CONFIG_COMMON_CLK_CS2000_CP is not set\n# CONFIG_XILINX_VCU is not set\n# CONFIG_HWSPINLOCK is not set\n\n#\n# Clock Source drivers\n#\nCONFIG_CLKEVT_I8253=y\nCONFIG_I8253_LOCK=y\nCONFIG_CLKBLD_I8253=y\n# end of Clock Source drivers\n\nCONFIG_MAILBOX=y\nCONFIG_PCC=y\n# CONFIG_ALTERA_MBOX is not set\nCONFIG_IOMMU_IOVA=y\nCONFIG_IOMMU_API=y\nCONFIG_IOMMU_SUPPORT=y\n\n#\n# Generic IOMMU Pagetable Support\n#\n# end of Generic IOMMU Pagetable Support\n\n# CONFIG_IOMMU_DEBUGFS is not set\n# CONFIG_IOMMU_DEFAULT_DMA_STRICT is not set\nCONFIG_IOMMU_DEFAULT_DMA_LAZY=y\n# CONFIG_IOMMU_DEFAULT_PASSTHROUGH is not set\nCONFIG_IOMMU_DMA=y\nCONFIG_IOMMU_SVA=y\nCONFIG_IOMMU_IOPF=y\nCONFIG_AMD_IOMMU=y\nCONFIG_DMAR_TABLE=y\nCONFIG_INTEL_IOMMU=y\n# CONFIG_INTEL_IOMMU_SVM is not set\n# CONFIG_INTEL_IOMMU_DEFAULT_ON is not set\n# CONFIG_INTEL_IOMMU_SCALABLE_MODE_DEFAULT_ON is not set\nCONFIG_INTEL_IOMMU_PERF_EVENTS=y\n# CONFIG_IOMMUFD is not set\n# CONFIG_IRQ_REMAP is not set\n# CONFIG_VIRTIO_IOMMU is not set\nCONFIG_GENERIC_PT=y\n# CONFIG_DEBUG_GENERIC_PT is not set\nCONFIG_IOMMU_PT=y\nCONFIG_IOMMU_PT_AMDV1=y\nCONFIG_IOMMU_PT_VTDSS=y\nCONFIG_IOMMU_PT_X86_64=y\n\n#\n# Remoteproc drivers\n#\n# CONFIG_REMOTEPROC is not set\n# end of Remoteproc drivers\n\n#\n# Rpmsg drivers\n#\n# CONFIG_RPMSG_QCOM_GLINK_RPM is not set\n# CONFIG_RPMSG_VIRTIO is not set\n# end of Rpmsg drivers\n\n#\n# SOC (System On Chip) specific Drivers\n#\n\n#\n# Amlogic SoC drivers\n#\n# end of Amlogic SoC drivers\n\n#\n# Broadcom SoC drivers\n#\n# end of Broadcom SoC drivers\n\n#\n# NXP/Freescale QorIQ SoC drivers\n#\n# end of NXP/Freescale QorIQ SoC drivers\n\n#\n# fujitsu SoC drivers\n#\n# end of fujitsu SoC drivers\n\n#\n# i.MX SoC drivers\n#\n# end of i.MX SoC drivers\n\n#\n# Enable LiteX SoC Builder specific drivers\n#\n# end of Enable LiteX SoC Builder specific drivers\n\n# CONFIG_WPCM450_SOC is not set\n\n#\n# Qualcomm SoC drivers\n#\n# end of Qualcomm SoC drivers\n\n# CONFIG_SOC_TI is not set\n\n#\n# Xilinx SoC drivers\n#\n# end of Xilinx SoC drivers\n# end of SOC (System On Chip) specific Drivers\n\n#\n# PM Domains\n#\n\n#\n# Amlogic PM Domains\n#\n# end of Amlogic PM Domains\n\n#\n# Broadcom PM Domains\n#\n# end of Broadcom PM Domains\n\n#\n# i.MX PM Domains\n#\n# end of i.MX PM Domains\n\n#\n# Qualcomm PM Domains\n#\n# end of Qualcomm PM Domains\n# end of PM Domains\n\n# CONFIG_PM_DEVFREQ is not set\n# CONFIG_EXTCON is not set\n# CONFIG_MEMORY is not set\n# CONFIG_IIO is not set\n# CONFIG_NTB is not set\n# CONFIG_PWM is not set\n\n#\n# IRQ chip support\n#\nCONFIG_IRQ_MSI_LIB=y\n# end of IRQ chip support\n\n# CONFIG_IPACK_BUS is not set\n# CONFIG_RESET_CONTROLLER is not set\n\n#\n# PHY Subsystem\n#\n# CONFIG_GENERIC_PHY is not set\n# CONFIG_USB_LGM_PHY is not set\n# CONFIG_PHY_CAN_TRANSCEIVER is not set\n\n#\n# PHY drivers for Broadcom platforms\n#\n# CONFIG_BCM_KONA_USB2_PHY is not set\n# end of PHY drivers for Broadcom platforms\n\n# CONFIG_PHY_PXA_28NM_HSIC is not set\n# CONFIG_PHY_PXA_28NM_USB2 is not set\n# CONFIG_PHY_INTEL_LGM_EMMC is not set\n# end of PHY Subsystem\n\n# CONFIG_POWERCAP is not set\n# CONFIG_MCB is not set\n\n#\n# Performance monitor support\n#\n# CONFIG_DWC_PCIE_PMU is not set\n# end of Performance monitor support\n\nCONFIG_RAS=y\n# CONFIG_USB4 is not set\n\n#\n# Android\n#\n# CONFIG_ANDROID_BINDER_IPC is not set\n# end of Android\n\n# CONFIG_LIBNVDIMM is not set\n# CONFIG_DAX is not set\nCONFIG_NVMEM=y\nCONFIG_NVMEM_SYSFS=y\n# CONFIG_NVMEM_LAYOUTS is not set\n# CONFIG_NVMEM_RMEM is not set\n\n#\n# HW tracing support\n#\n# CONFIG_STM is not set\n# CONFIG_INTEL_TH is not set\n# end of HW tracing support\n\n# CONFIG_FPGA is not set\n# CONFIG_TEE is not set\n# CONFIG_SIOX is not set\n# CONFIG_SLIMBUS is not set\n# CONFIG_INTERCONNECT is not set\n# CONFIG_COUNTER is not set\n# CONFIG_MOST is not set\n# CONFIG_PECI is not set\n# CONFIG_HTE is not set\n# end of Device Drivers\n\n#\n# File systems\n#\nCONFIG_DCACHE_WORD_ACCESS=y\n# CONFIG_VALIDATE_FS_PARSER is not set\nCONFIG_FS_IOMAP=y\nCONFIG_FS_STACK=y\nCONFIG_BUFFER_HEAD=y\nCONFIG_LEGACY_DIRECT_IO=y\n# CONFIG_EXT2_FS is not set\n# CONFIG_EXT4_FS is not set\n# CONFIG_JFS_FS is not set\n# CONFIG_XFS_FS is not set\n# CONFIG_GFS2_FS is not set\n# CONFIG_OCFS2_FS is not set\n# CONFIG_BTRFS_FS is not set\n# CONFIG_NILFS2_FS is not set\n# CONFIG_F2FS_FS is not set\nCONFIG_FS_POSIX_ACL=y\nCONFIG_EXPORTFS=y\n# CONFIG_EXPORTFS_BLOCK_OPS is not set\nCONFIG_FILE_LOCKING=y\n# CONFIG_FS_ENCRYPTION is not set\n# CONFIG_FS_VERITY is not set\nCONFIG_FSNOTIFY=y\nCONFIG_DNOTIFY=y\nCONFIG_INOTIFY_USER=y\nCONFIG_FANOTIFY=y\n# CONFIG_FANOTIFY_ACCESS_PERMISSIONS is not set\nCONFIG_QUOTA=y\nCONFIG_QUOTA_NETLINK_INTERFACE=y\n# CONFIG_QUOTA_DEBUG is not set\nCONFIG_QUOTA_TREE=y\n# CONFIG_QFMT_V1 is not set\nCONFIG_QFMT_V2=y\nCONFIG_QUOTACTL=y\nCONFIG_AUTOFS_FS=y\nCONFIG_FUSE_FS=y\nCONFIG_CUSE=y\nCONFIG_VIRTIO_FS=y\nCONFIG_FUSE_PASSTHROUGH=y\nCONFIG_FUSE_IO_URING=y\nCONFIG_OVERLAY_FS=y\n# CONFIG_OVERLAY_FS_REDIRECT_DIR is not set\nCONFIG_OVERLAY_FS_REDIRECT_ALWAYS_FOLLOW=y\n# CONFIG_OVERLAY_FS_INDEX is not set\n# CONFIG_OVERLAY_FS_XINO_AUTO is not set\n# CONFIG_OVERLAY_FS_METACOPY is not set\n# CONFIG_OVERLAY_FS_DEBUG is not set\n\n#\n# Caches\n#\nCONFIG_NETFS_SUPPORT=y\n# CONFIG_NETFS_STATS is not set\n# CONFIG_NETFS_DEBUG is not set\n# CONFIG_FSCACHE is not set\n# end of Caches\n\n#\n# CD-ROM/DVD Filesystems\n#\nCONFIG_ISO9660_FS=y\nCONFIG_JOLIET=y\nCONFIG_ZISOFS=y\n# CONFIG_UDF_FS is not set\n# end of CD-ROM/DVD Filesystems\n\n#\n# DOS/FAT/EXFAT/NT Filesystems\n#\nCONFIG_FAT_FS=y\nCONFIG_MSDOS_FS=y\nCONFIG_VFAT_FS=y\nCONFIG_FAT_DEFAULT_CODEPAGE=437\nCONFIG_FAT_DEFAULT_IOCHARSET=\"iso8859-1\"\n# CONFIG_FAT_DEFAULT_UTF8 is not set\n# CONFIG_EXFAT_FS is not set\n# CONFIG_NTFS3_FS is not set\n# CONFIG_NTFS_FS is not set\n# end of DOS/FAT/EXFAT/NT Filesystems\n\n#\n# Pseudo filesystems\n#\nCONFIG_PROC_FS=y\nCONFIG_PROC_KCORE=y\nCONFIG_PROC_VMCORE=y\n# CONFIG_PROC_VMCORE_DEVICE_DUMP is not set\nCONFIG_PROC_SYSCTL=y\nCONFIG_PROC_PAGE_MONITOR=y\nCONFIG_PROC_CHILDREN=y\nCONFIG_PROC_PID_ARCH_STATUS=y\nCONFIG_KERNFS=y\nCONFIG_SYSFS=y\nCONFIG_TMPFS=y\nCONFIG_TMPFS_POSIX_ACL=y\nCONFIG_TMPFS_XATTR=y\n# CONFIG_TMPFS_INODE64 is not set\n# CONFIG_TMPFS_QUOTA is not set\nCONFIG_ARCH_SUPPORTS_HUGETLBFS=y\nCONFIG_HUGETLBFS=y\n# CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP_DEFAULT_ON is not set\nCONFIG_HUGETLB_PAGE=y\nCONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP=y\nCONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING=y\nCONFIG_ARCH_HAS_GIGANTIC_PAGE=y\nCONFIG_CONFIGFS_FS=y\nCONFIG_EFIVAR_FS=y\n# end of Pseudo filesystems\n\nCONFIG_MISC_FILESYSTEMS=y\n# CONFIG_ORANGEFS_FS is not set\n# CONFIG_ADFS_FS is not set\n# CONFIG_AFFS_FS is not set\n# CONFIG_ECRYPT_FS is not set\n# CONFIG_HFS_FS is not set\n# CONFIG_HFSPLUS_FS is not set\n# CONFIG_BEFS_FS is not set\n# CONFIG_BFS_FS is not set\n# CONFIG_EFS_FS is not set\n# CONFIG_CRAMFS is not set\n# CONFIG_SQUASHFS is not set\n# CONFIG_VXFS_FS is not set\n# CONFIG_MINIX_FS is not set\n# CONFIG_OMFS_FS is not set\n# CONFIG_HPFS_FS is not set\n# CONFIG_QNX4FS_FS is not set\n# CONFIG_QNX6FS_FS is not set\n# CONFIG_ROMFS_FS is not set\n# CONFIG_PSTORE is not set\n# CONFIG_UFS_FS is not set\n# CONFIG_EROFS_FS is not set\nCONFIG_NETWORK_FILESYSTEMS=y\nCONFIG_NFS_FS=y\nCONFIG_NFS_V2=y\nCONFIG_NFS_V3=y\nCONFIG_NFS_V3_ACL=y\nCONFIG_NFS_V4=y\n# CONFIG_NFS_SWAP is not set\n# CONFIG_NFS_V4_1 is not set\nCONFIG_ROOT_NFS=y\n# CONFIG_NFS_FSCACHE is not set\n# CONFIG_NFS_USE_LEGACY_DNS is not set\nCONFIG_NFS_USE_KERNEL_DNS=y\nCONFIG_NFS_DISABLE_UDP_SUPPORT=y\n# CONFIG_NFSD is not set\nCONFIG_GRACE_PERIOD=y\nCONFIG_LOCKD=y\nCONFIG_LOCKD_V4=y\nCONFIG_NFS_ACL_SUPPORT=y\nCONFIG_NFS_COMMON=y\nCONFIG_SUNRPC=y\n# CONFIG_RPCSEC_GSS_KRB5 is not set\n# CONFIG_SUNRPC_DEBUG is not set\n# CONFIG_CEPH_FS is not set\n# CONFIG_CIFS is not set\n# CONFIG_SMB_SERVER is not set\n# CONFIG_CODA_FS is not set\n# CONFIG_AFS_FS is not set\nCONFIG_9P_FS=y\nCONFIG_9P_FS_POSIX_ACL=y\nCONFIG_9P_FS_SECURITY=y\nCONFIG_NLS=y\nCONFIG_NLS_DEFAULT=\"utf8\"\nCONFIG_NLS_CODEPAGE_437=y\n# CONFIG_NLS_CODEPAGE_737 is not set\n# CONFIG_NLS_CODEPAGE_775 is not set\n# CONFIG_NLS_CODEPAGE_850 is not set\n# CONFIG_NLS_CODEPAGE_852 is not set\n# CONFIG_NLS_CODEPAGE_855 is not set\n# CONFIG_NLS_CODEPAGE_857 is not set\n# CONFIG_NLS_CODEPAGE_860 is not set\n# CONFIG_NLS_CODEPAGE_861 is not set\n# CONFIG_NLS_CODEPAGE_862 is not set\n# CONFIG_NLS_CODEPAGE_863 is not set\n# CONFIG_NLS_CODEPAGE_864 is not set\n# CONFIG_NLS_CODEPAGE_865 is not set\n# CONFIG_NLS_CODEPAGE_866 is not set\n# CONFIG_NLS_CODEPAGE_869 is not set\n# CONFIG_NLS_CODEPAGE_936 is not set\n# CONFIG_NLS_CODEPAGE_950 is not set\n# CONFIG_NLS_CODEPAGE_932 is not set\n# CONFIG_NLS_CODEPAGE_949 is not set\n# CONFIG_NLS_CODEPAGE_874 is not set\n# CONFIG_NLS_ISO8859_8 is not set\n# CONFIG_NLS_CODEPAGE_1250 is not set\n# CONFIG_NLS_CODEPAGE_1251 is not set\nCONFIG_NLS_ASCII=y\nCONFIG_NLS_ISO8859_1=y\n# CONFIG_NLS_ISO8859_2 is not set\n# CONFIG_NLS_ISO8859_3 is not set\n# CONFIG_NLS_ISO8859_4 is not set\n# CONFIG_NLS_ISO8859_5 is not set\n# CONFIG_NLS_ISO8859_6 is not set\n# CONFIG_NLS_ISO8859_7 is not set\n# CONFIG_NLS_ISO8859_9 is not set\n# CONFIG_NLS_ISO8859_13 is not set\n# CONFIG_NLS_ISO8859_14 is not set\n# CONFIG_NLS_ISO8859_15 is not set\n# CONFIG_NLS_KOI8_R is not set\n# CONFIG_NLS_KOI8_U is not set\n# CONFIG_NLS_MAC_ROMAN is not set\n# CONFIG_NLS_MAC_CELTIC is not set\n# CONFIG_NLS_MAC_CENTEURO is not set\n# CONFIG_NLS_MAC_CROATIAN is not set\n# CONFIG_NLS_MAC_CYRILLIC is not set\n# CONFIG_NLS_MAC_GAELIC is not set\n# CONFIG_NLS_MAC_GREEK is not set\n# CONFIG_NLS_MAC_ICELAND is not set\n# CONFIG_NLS_MAC_INUIT is not set\n# CONFIG_NLS_MAC_ROMANIAN is not set\n# CONFIG_NLS_MAC_TURKISH is not set\nCONFIG_NLS_UTF8=y\n# CONFIG_DLM is not set\n# CONFIG_UNICODE is not set\nCONFIG_IO_WQ=y\n# end of File systems\n\n#\n# Security options\n#\nCONFIG_KEYS=y\n# CONFIG_KEYS_REQUEST_CACHE is not set\n# CONFIG_PERSISTENT_KEYRINGS is not set\n# CONFIG_BIG_KEYS is not set\n# CONFIG_TRUSTED_KEYS is not set\n# CONFIG_ENCRYPTED_KEYS is not set\n# CONFIG_KEY_DH_OPERATIONS is not set\n# CONFIG_SECURITY_DMESG_RESTRICT is not set\nCONFIG_PROC_MEM_ALWAYS_FORCE=y\n# CONFIG_PROC_MEM_FORCE_PTRACE is not set\n# CONFIG_PROC_MEM_NO_FORCE is not set\n# CONFIG_MSEAL_SYSTEM_MAPPINGS is not set\nCONFIG_SECURITY=y\nCONFIG_HAS_SECURITY_AUDIT=y\nCONFIG_SECURITYFS=y\nCONFIG_SECURITY_NETWORK=y\n# CONFIG_SECURITY_NETWORK_XFRM is not set\nCONFIG_SECURITY_PATH=y\n# CONFIG_INTEL_TXT is not set\n# CONFIG_STATIC_USERMODEHELPER is not set\n# CONFIG_SECURITY_SELINUX is not set\n# CONFIG_SECURITY_SMACK is not set\n# CONFIG_SECURITY_TOMOYO is not set\n# CONFIG_SECURITY_APPARMOR is not set\n# CONFIG_SECURITY_LOADPIN is not set\nCONFIG_SECURITY_YAMA=y\n# CONFIG_SECURITY_SAFESETID is not set\n# CONFIG_SECURITY_LOCKDOWN_LSM is not set\n# CONFIG_SECURITY_LANDLOCK is not set\n# CONFIG_SECURITY_IPE is not set\nCONFIG_INTEGRITY=y\n# CONFIG_INTEGRITY_SIGNATURE is not set\nCONFIG_INTEGRITY_AUDIT=y\nCONFIG_IMA=y\nCONFIG_IMA_MEASURE_PCR_IDX=10\nCONFIG_IMA_NG_TEMPLATE=y\n# CONFIG_IMA_SIG_TEMPLATE is not set\nCONFIG_IMA_DEFAULT_TEMPLATE=\"ima-ng\"\nCONFIG_IMA_DEFAULT_HASH_SHA1=y\n# CONFIG_IMA_DEFAULT_HASH_SHA256 is not set\n# CONFIG_IMA_DEFAULT_HASH_SHA512 is not set\nCONFIG_IMA_DEFAULT_HASH=\"sha1\"\nCONFIG_IMA_WRITE_POLICY=y\nCONFIG_IMA_READ_POLICY=y\n# CONFIG_IMA_APPRAISE is not set\nCONFIG_IMA_MEASURE_ASYMMETRIC_KEYS=y\nCONFIG_IMA_QUEUE_EARLY_BOOT_KEYS=y\n# CONFIG_IMA_SECURE_AND_OR_TRUSTED_BOOT is not set\n# CONFIG_IMA_DISABLE_HTABLE is not set\n# CONFIG_EVM is not set\nCONFIG_DEFAULT_SECURITY_DAC=y\nCONFIG_LSM=\"lockdown,yama,loadpin,safesetid,integrity,selinux,smack,tomoyo,apparmor,bpf\"\n\n#\n# Kernel hardening options\n#\n\n#\n# Memory initialization\n#\nCONFIG_CC_HAS_AUTO_VAR_INIT_PATTERN=y\nCONFIG_CC_HAS_AUTO_VAR_INIT_ZERO_BARE=y\nCONFIG_CC_HAS_AUTO_VAR_INIT_ZERO=y\nCONFIG_INIT_STACK_NONE=y\n# CONFIG_INIT_STACK_ALL_PATTERN is not set\n# CONFIG_INIT_STACK_ALL_ZERO is not set\nCONFIG_CC_HAS_SANCOV_STACK_DEPTH_CALLBACK=y\n# CONFIG_KSTACK_ERASE is not set\n# CONFIG_INIT_ON_ALLOC_DEFAULT_ON is not set\n# CONFIG_INIT_ON_FREE_DEFAULT_ON is not set\nCONFIG_CC_HAS_ZERO_CALL_USED_REGS=y\n# CONFIG_ZERO_CALL_USED_REGS is not set\n# end of Memory initialization\n\n#\n# Bounds checking\n#\n# CONFIG_FORTIFY_SOURCE is not set\n# CONFIG_HARDENED_USERCOPY is not set\n# end of Bounds checking\n\n#\n# Hardening of kernel data structures\n#\n# CONFIG_LIST_HARDENED is not set\n# CONFIG_BUG_ON_DATA_CORRUPTION is not set\n# end of Hardening of kernel data structures\n\nCONFIG_CC_HAS_RANDSTRUCT=y\nCONFIG_RANDSTRUCT_NONE=y\n# CONFIG_RANDSTRUCT_FULL is not set\n# end of Kernel hardening options\n# end of Security options\n\nCONFIG_CRYPTO=y\n\n#\n# Crypto core or helper\n#\nCONFIG_CRYPTO_ALGAPI=y\nCONFIG_CRYPTO_ALGAPI2=y\nCONFIG_CRYPTO_AEAD=y\nCONFIG_CRYPTO_AEAD2=y\nCONFIG_CRYPTO_SIG=y\nCONFIG_CRYPTO_SIG2=y\nCONFIG_CRYPTO_SKCIPHER=y\nCONFIG_CRYPTO_SKCIPHER2=y\nCONFIG_CRYPTO_HASH=y\nCONFIG_CRYPTO_HASH2=y\nCONFIG_CRYPTO_RNG=y\nCONFIG_CRYPTO_RNG2=y\nCONFIG_CRYPTO_RNG_DEFAULT=y\nCONFIG_CRYPTO_AKCIPHER2=y\nCONFIG_CRYPTO_AKCIPHER=y\nCONFIG_CRYPTO_KPP2=y\nCONFIG_CRYPTO_ACOMP2=y\nCONFIG_CRYPTO_MANAGER=y\nCONFIG_CRYPTO_MANAGER2=y\n# CONFIG_CRYPTO_USER is not set\n# CONFIG_CRYPTO_SELFTESTS is not set\nCONFIG_CRYPTO_NULL=y\n# CONFIG_CRYPTO_PCRYPT is not set\n# CONFIG_CRYPTO_CRYPTD is not set\nCONFIG_CRYPTO_AUTHENC=y\n# CONFIG_CRYPTO_KRB5ENC is not set\n# CONFIG_CRYPTO_BENCHMARK is not set\n# end of Crypto core or helper\n\n#\n# Public-key cryptography\n#\nCONFIG_CRYPTO_RSA=y\n# CONFIG_CRYPTO_DH is not set\n# CONFIG_CRYPTO_ECDH is not set\n# CONFIG_CRYPTO_ECDSA is not set\n# CONFIG_CRYPTO_ECRDSA is not set\n# end of Public-key cryptography\n\n#\n# Block ciphers\n#\nCONFIG_CRYPTO_AES=y\n# CONFIG_CRYPTO_AES_TI is not set\n# CONFIG_CRYPTO_ANUBIS is not set\n# CONFIG_CRYPTO_ARIA is not set\n# CONFIG_CRYPTO_BLOWFISH is not set\n# CONFIG_CRYPTO_CAMELLIA is not set\n# CONFIG_CRYPTO_CAST5 is not set\n# CONFIG_CRYPTO_CAST6 is not set\n# CONFIG_CRYPTO_DES is not set\n# CONFIG_CRYPTO_FCRYPT is not set\n# CONFIG_CRYPTO_KHAZAD is not set\n# CONFIG_CRYPTO_SEED is not set\n# CONFIG_CRYPTO_SERPENT is not set\n# CONFIG_CRYPTO_SM4_GENERIC is not set\n# CONFIG_CRYPTO_TEA is not set\n# CONFIG_CRYPTO_TWOFISH is not set\n# end of Block ciphers\n\n#\n# Length-preserving ciphers and modes\n#\n# CONFIG_CRYPTO_ADIANTUM is not set\n# CONFIG_CRYPTO_ARC4 is not set\n# CONFIG_CRYPTO_CHACHA20 is not set\nCONFIG_CRYPTO_CBC=y\nCONFIG_CRYPTO_CTR=y\n# CONFIG_CRYPTO_CTS is not set\nCONFIG_CRYPTO_ECB=y\n# CONFIG_CRYPTO_HCTR2 is not set\n# CONFIG_CRYPTO_LRW is not set\n# CONFIG_CRYPTO_PCBC is not set\n# CONFIG_CRYPTO_XTS is not set\n# end of Length-preserving ciphers and modes\n\n#\n# AEAD (authenticated encryption with associated data) ciphers\n#\n# CONFIG_CRYPTO_AEGIS128 is not set\n# CONFIG_CRYPTO_CHACHA20POLY1305 is not set\nCONFIG_CRYPTO_CCM=y\nCONFIG_CRYPTO_GCM=y\nCONFIG_CRYPTO_GENIV=y\nCONFIG_CRYPTO_SEQIV=y\nCONFIG_CRYPTO_ECHAINIV=y\n# CONFIG_CRYPTO_ESSIV is not set\n# end of AEAD (authenticated encryption with associated data) ciphers\n\n#\n# Hashes, digests, and MACs\n#\nCONFIG_CRYPTO_BLAKE2B=y\nCONFIG_CRYPTO_CMAC=y\nCONFIG_CRYPTO_GHASH=y\nCONFIG_CRYPTO_HMAC=y\n# CONFIG_CRYPTO_MD4 is not set\nCONFIG_CRYPTO_MD5=y\n# CONFIG_CRYPTO_MICHAEL_MIC is not set\n# CONFIG_CRYPTO_RMD160 is not set\nCONFIG_CRYPTO_SHA1=y\nCONFIG_CRYPTO_SHA256=y\nCONFIG_CRYPTO_SHA512=y\nCONFIG_CRYPTO_SHA3=y\n# CONFIG_CRYPTO_SM3_GENERIC is not set\n# CONFIG_CRYPTO_STREEBOG is not set\n# CONFIG_CRYPTO_WP512 is not set\n# CONFIG_CRYPTO_XCBC is not set\nCONFIG_CRYPTO_XXHASH=y\n# end of Hashes, digests, and MACs\n\n#\n# CRCs (cyclic redundancy checks)\n#\nCONFIG_CRYPTO_CRC32C=y\n# CONFIG_CRYPTO_CRC32 is not set\n# end of CRCs (cyclic redundancy checks)\n\n#\n# Compression\n#\n# CONFIG_CRYPTO_DEFLATE is not set\nCONFIG_CRYPTO_LZO=y\n# CONFIG_CRYPTO_842 is not set\n# CONFIG_CRYPTO_LZ4 is not set\n# CONFIG_CRYPTO_LZ4HC is not set\n# CONFIG_CRYPTO_ZSTD is not set\n# end of Compression\n\n#\n# Random number generation\n#\nCONFIG_CRYPTO_DRBG_MENU=y\nCONFIG_CRYPTO_DRBG_HMAC=y\n# CONFIG_CRYPTO_DRBG_HASH is not set\n# CONFIG_CRYPTO_DRBG_CTR is not set\nCONFIG_CRYPTO_DRBG=y\nCONFIG_CRYPTO_JITTERENTROPY=y\nCONFIG_CRYPTO_JITTERENTROPY_MEMORY_BLOCKS=64\nCONFIG_CRYPTO_JITTERENTROPY_MEMORY_BLOCKSIZE=32\nCONFIG_CRYPTO_JITTERENTROPY_OSR=1\n# end of Random number generation\n\n#\n# Userspace interface\n#\nCONFIG_CRYPTO_USER_API=y\nCONFIG_CRYPTO_USER_API_HASH=y\n# CONFIG_CRYPTO_USER_API_SKCIPHER is not set\n# CONFIG_CRYPTO_USER_API_RNG is not set\n# CONFIG_CRYPTO_USER_API_AEAD is not set\nCONFIG_CRYPTO_USER_API_ENABLE_OBSOLETE=y\n# end of Userspace interface\n\n#\n# Accelerated Cryptographic Algorithms for CPU (x86)\n#\n# CONFIG_CRYPTO_AES_NI_INTEL is not set\n# CONFIG_CRYPTO_BLOWFISH_X86_64 is not set\n# CONFIG_CRYPTO_CAMELLIA_X86_64 is not set\n# CONFIG_CRYPTO_CAMELLIA_AESNI_AVX_X86_64 is not set\n# CONFIG_CRYPTO_CAMELLIA_AESNI_AVX2_X86_64 is not set\n# CONFIG_CRYPTO_CAST5_AVX_X86_64 is not set\n# CONFIG_CRYPTO_CAST6_AVX_X86_64 is not set\n# CONFIG_CRYPTO_DES3_EDE_X86_64 is not set\n# CONFIG_CRYPTO_SERPENT_SSE2_X86_64 is not set\n# CONFIG_CRYPTO_SERPENT_AVX_X86_64 is not set\n# CONFIG_CRYPTO_SERPENT_AVX2_X86_64 is not set\n# CONFIG_CRYPTO_SM4_AESNI_AVX_X86_64 is not set\n# CONFIG_CRYPTO_SM4_AESNI_AVX2_X86_64 is not set\n# CONFIG_CRYPTO_TWOFISH_X86_64 is not set\n# CONFIG_CRYPTO_TWOFISH_X86_64_3WAY is not set\n# CONFIG_CRYPTO_TWOFISH_AVX_X86_64 is not set\n# CONFIG_CRYPTO_ARIA_AESNI_AVX_X86_64 is not set\n# CONFIG_CRYPTO_ARIA_AESNI_AVX2_X86_64 is not set\n# CONFIG_CRYPTO_ARIA_GFNI_AVX512_X86_64 is not set\n# CONFIG_CRYPTO_AEGIS128_AESNI_SSE2 is not set\n# CONFIG_CRYPTO_NHPOLY1305_SSE2 is not set\n# CONFIG_CRYPTO_NHPOLY1305_AVX2 is not set\n# CONFIG_CRYPTO_SM3_AVX_X86_64 is not set\n# CONFIG_CRYPTO_GHASH_CLMUL_NI_INTEL is not set\n# end of Accelerated Cryptographic Algorithms for CPU (x86)\n\nCONFIG_CRYPTO_HW=y\n# CONFIG_CRYPTO_DEV_PADLOCK is not set\n# CONFIG_CRYPTO_DEV_ATMEL_ECC is not set\n# CONFIG_CRYPTO_DEV_ATMEL_SHA204A is not set\n# CONFIG_CRYPTO_DEV_CCP is not set\n# CONFIG_CRYPTO_DEV_NITROX_CNN55XX is not set\n# CONFIG_CRYPTO_DEV_QAT_DH895xCC is not set\n# CONFIG_CRYPTO_DEV_QAT_C3XXX is not set\n# CONFIG_CRYPTO_DEV_QAT_C62X is not set\n# CONFIG_CRYPTO_DEV_QAT_4XXX is not set\n# CONFIG_CRYPTO_DEV_QAT_420XX is not set\n# CONFIG_CRYPTO_DEV_QAT_6XXX is not set\n# CONFIG_CRYPTO_DEV_QAT_DH895xCCVF is not set\n# CONFIG_CRYPTO_DEV_QAT_C3XXXVF is not set\n# CONFIG_CRYPTO_DEV_QAT_C62XVF is not set\n# CONFIG_CRYPTO_DEV_VIRTIO is not set\n# CONFIG_CRYPTO_DEV_SAFEXCEL is not set\n# CONFIG_CRYPTO_DEV_AMLOGIC_GXL is not set\nCONFIG_ASYMMETRIC_KEY_TYPE=y\nCONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE=y\nCONFIG_X509_CERTIFICATE_PARSER=y\n# CONFIG_PKCS8_PRIVATE_KEY_PARSER is not set\nCONFIG_PKCS7_MESSAGE_PARSER=y\n# CONFIG_PKCS7_TEST_KEY is not set\n# CONFIG_SIGNED_PE_FILE_VERIFICATION is not set\n# CONFIG_FIPS_SIGNATURE_SELFTEST is not set\n\n#\n# Certificates for signature checking\n#\nCONFIG_SYSTEM_TRUSTED_KEYRING=y\nCONFIG_SYSTEM_TRUSTED_KEYS=\"\"\n# CONFIG_SYSTEM_EXTRA_CERTIFICATE is not set\n# CONFIG_SECONDARY_TRUSTED_KEYRING is not set\n# CONFIG_SYSTEM_BLACKLIST_KEYRING is not set\n# end of Certificates for signature checking\n\n# CONFIG_CRYPTO_KRB5 is not set\nCONFIG_BINARY_PRINTF=y\n\n#\n# Library routines\n#\n# CONFIG_PACKING is not set\nCONFIG_BITREVERSE=y\nCONFIG_GENERIC_STRNCPY_FROM_USER=y\nCONFIG_GENERIC_STRNLEN_USER=y\nCONFIG_GENERIC_NET_UTILS=y\n# CONFIG_CORDIC is not set\n# CONFIG_PRIME_NUMBERS is not set\nCONFIG_RATIONAL=y\nCONFIG_GENERIC_IOMAP=y\nCONFIG_ARCH_USE_CMPXCHG_LOCKREF=y\nCONFIG_ARCH_HAS_FAST_MULTIPLIER=y\nCONFIG_ARCH_USE_SYM_ANNOTATIONS=y\nCONFIG_CRC_CCITT=y\nCONFIG_CRC32=y\nCONFIG_CRC32_ARCH=y\nCONFIG_CRC_OPTIMIZATIONS=y\n\n#\n# Crypto library routines\n#\nCONFIG_CRYPTO_HASH_INFO=y\nCONFIG_CRYPTO_LIB_UTILS=y\nCONFIG_CRYPTO_LIB_AES=y\nCONFIG_CRYPTO_LIB_ARC4=y\nCONFIG_CRYPTO_LIB_GF128MUL=y\nCONFIG_CRYPTO_LIB_BLAKE2B=y\nCONFIG_CRYPTO_LIB_BLAKE2S_ARCH=y\nCONFIG_CRYPTO_LIB_MD5=y\nCONFIG_CRYPTO_LIB_POLY1305_RSIZE=11\nCONFIG_CRYPTO_LIB_SHA1=y\nCONFIG_CRYPTO_LIB_SHA1_ARCH=y\nCONFIG_CRYPTO_LIB_SHA256=y\nCONFIG_CRYPTO_LIB_SHA256_ARCH=y\nCONFIG_CRYPTO_LIB_SHA512=y\nCONFIG_CRYPTO_LIB_SHA512_ARCH=y\nCONFIG_CRYPTO_LIB_SHA3=y\n# end of Crypto library routines\n\nCONFIG_XXHASH=y\n# CONFIG_RANDOM32_SELFTEST is not set\nCONFIG_ZLIB_INFLATE=y\nCONFIG_LZO_COMPRESS=y\nCONFIG_LZO_DECOMPRESS=y\nCONFIG_LZ4_DECOMPRESS=y\nCONFIG_ZSTD_COMMON=y\nCONFIG_ZSTD_DECOMPRESS=y\nCONFIG_XZ_DEC=y\nCONFIG_XZ_DEC_X86=y\nCONFIG_XZ_DEC_POWERPC=y\nCONFIG_XZ_DEC_ARM=y\nCONFIG_XZ_DEC_ARMTHUMB=y\nCONFIG_XZ_DEC_ARM64=y\nCONFIG_XZ_DEC_SPARC=y\nCONFIG_XZ_DEC_RISCV=y\n# CONFIG_XZ_DEC_MICROLZMA is not set\nCONFIG_XZ_DEC_BCJ=y\n# CONFIG_XZ_DEC_TEST is not set\nCONFIG_DECOMPRESS_GZIP=y\nCONFIG_DECOMPRESS_BZIP2=y\nCONFIG_DECOMPRESS_LZMA=y\nCONFIG_DECOMPRESS_XZ=y\nCONFIG_DECOMPRESS_LZO=y\nCONFIG_DECOMPRESS_LZ4=y\nCONFIG_DECOMPRESS_ZSTD=y\nCONFIG_GENERIC_ALLOCATOR=y\nCONFIG_INTERVAL_TREE=y\nCONFIG_XARRAY_MULTI=y\nCONFIG_ASSOCIATIVE_ARRAY=y\nCONFIG_HAS_IOMEM=y\nCONFIG_HAS_IOPORT=y\nCONFIG_HAS_IOPORT_MAP=y\nCONFIG_HAS_DMA=y\nCONFIG_DMA_OPS_HELPERS=y\nCONFIG_NEED_SG_DMA_FLAGS=y\nCONFIG_NEED_SG_DMA_LENGTH=y\nCONFIG_NEED_DMA_MAP_STATE=y\nCONFIG_ARCH_DMA_ADDR_T_64BIT=y\nCONFIG_SWIOTLB=y\n# CONFIG_SWIOTLB_DYNAMIC is not set\nCONFIG_DMA_NEED_SYNC=y\n# CONFIG_DMA_API_DEBUG is not set\n# CONFIG_DMA_MAP_BENCHMARK is not set\nCONFIG_SGL_ALLOC=y\nCONFIG_CHECK_SIGNATURE=y\nCONFIG_CPU_RMAP=y\nCONFIG_DQL=y\nCONFIG_GLOB=y\n# CONFIG_GLOB_SELFTEST is not set\nCONFIG_NLATTR=y\nCONFIG_CLZ_TAB=y\n# CONFIG_IRQ_POLL is not set\nCONFIG_MPILIB=y\nCONFIG_DIMLIB=y\nCONFIG_OID_REGISTRY=y\nCONFIG_UCS2_STRING=y\nCONFIG_HAVE_GENERIC_VDSO=y\nCONFIG_GENERIC_GETTIMEOFDAY=y\nCONFIG_GENERIC_VDSO_OVERFLOW_PROTECT=y\nCONFIG_VDSO_GETRANDOM=y\nCONFIG_FONT_SUPPORT=y\n# CONFIG_FONTS is not set\nCONFIG_FONT_8x8=y\nCONFIG_FONT_8x16=y\nCONFIG_SG_POOL=y\nCONFIG_ARCH_HAS_PMEM_API=y\nCONFIG_ARCH_HAS_CPU_CACHE_INVALIDATE_MEMREGION=y\nCONFIG_ARCH_HAS_UACCESS_FLUSHCACHE=y\nCONFIG_ARCH_HAS_COPY_MC=y\nCONFIG_ARCH_STACKWALK=y\nCONFIG_STACKDEPOT=y\nCONFIG_STACKDEPOT_MAX_FRAMES=64\nCONFIG_SBITMAP=y\n# CONFIG_LWQ_TEST is not set\n# end of Library routines\n\nCONFIG_FIRMWARE_TABLE=y\nCONFIG_UNION_FIND=y\n\n#\n# Kernel hacking\n#\n\n#\n# printk and dmesg options\n#\nCONFIG_PRINTK_TIME=y\nCONFIG_PRINTK_CALLER=y\n# CONFIG_STACKTRACE_BUILD_ID is not set\nCONFIG_CONSOLE_LOGLEVEL_DEFAULT=7\nCONFIG_CONSOLE_LOGLEVEL_QUIET=4\nCONFIG_MESSAGE_LOGLEVEL_DEFAULT=4\n# CONFIG_BOOT_PRINTK_DELAY is not set\n# CONFIG_DYNAMIC_DEBUG is not set\n# CONFIG_DYNAMIC_DEBUG_CORE is not set\nCONFIG_SYMBOLIC_ERRNAME=y\nCONFIG_DEBUG_BUGVERBOSE=y\nCONFIG_DEBUG_BUGVERBOSE_DETAILED=y\n# end of printk and dmesg options\n\nCONFIG_DEBUG_KERNEL=y\nCONFIG_DEBUG_MISC=y\n\n#\n# Compile-time checks and compiler options\n#\nCONFIG_DEBUG_INFO=y\nCONFIG_AS_HAS_NON_CONST_ULEB128=y\n# CONFIG_DEBUG_INFO_NONE is not set\nCONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y\n# CONFIG_DEBUG_INFO_DWARF4 is not set\n# CONFIG_DEBUG_INFO_DWARF5 is not set\n# CONFIG_DEBUG_INFO_REDUCED is not set\nCONFIG_DEBUG_INFO_COMPRESSED_NONE=y\n# CONFIG_DEBUG_INFO_COMPRESSED_ZLIB is not set\n# CONFIG_DEBUG_INFO_COMPRESSED_ZSTD is not set\n# CONFIG_DEBUG_INFO_SPLIT is not set\nCONFIG_DEBUG_INFO_BTF=y\nCONFIG_PAHOLE_HAS_SPLIT_BTF=y\nCONFIG_PAHOLE_HAS_BTF_TAG=y\nCONFIG_PAHOLE_HAS_LANG_EXCLUDE=y\nCONFIG_DEBUG_INFO_BTF_MODULES=y\n# CONFIG_MODULE_ALLOW_BTF_MISMATCH is not set\nCONFIG_GDB_SCRIPTS=y\nCONFIG_FRAME_WARN=2048\nCONFIG_STRIP_ASM_SYMS=y\nCONFIG_HEADERS_INSTALL=y\n# CONFIG_SECTION_MISMATCH_WARN_ONLY is not set\n# CONFIG_DEBUG_FORCE_FUNCTION_ALIGN_64B is not set\nCONFIG_OBJTOOL=y\n# CONFIG_OBJTOOL_WERROR is not set\nCONFIG_VMLINUX_MAP=y\n# CONFIG_DEBUG_FORCE_WEAK_PER_CPU is not set\n# end of Compile-time checks and compiler options\n\n#\n# Generic Kernel Debugging Instruments\n#\nCONFIG_MAGIC_SYSRQ=y\nCONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE=0x1\nCONFIG_MAGIC_SYSRQ_SERIAL=y\nCONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE=\"\"\nCONFIG_DEBUG_FS=y\nCONFIG_DEBUG_FS_ALLOW_ALL=y\n# CONFIG_DEBUG_FS_ALLOW_NONE is not set\nCONFIG_HAVE_ARCH_KGDB=y\n# CONFIG_KGDB is not set\nCONFIG_ARCH_HAS_UBSAN=y\n# CONFIG_UBSAN is not set\nCONFIG_HAVE_ARCH_KCSAN=y\nCONFIG_HAVE_KCSAN_COMPILER=y\n# CONFIG_KCSAN is not set\n# end of Generic Kernel Debugging Instruments\n\n#\n# Networking Debugging\n#\n# CONFIG_NET_DEV_REFCNT_TRACKER is not set\n# CONFIG_NET_NS_REFCNT_TRACKER is not set\n# CONFIG_DEBUG_NET is not set\n# CONFIG_DEBUG_NET_SMALL_RTNL is not set\n# end of Networking Debugging\n\n#\n# Memory Debugging\n#\n# CONFIG_PAGE_EXTENSION is not set\n# CONFIG_DEBUG_PAGEALLOC is not set\nCONFIG_SLUB_DEBUG=y\n# CONFIG_SLUB_DEBUG_ON is not set\n# CONFIG_PAGE_OWNER is not set\n# CONFIG_PAGE_TABLE_CHECK is not set\n# CONFIG_PAGE_POISONING is not set\n# CONFIG_DEBUG_PAGE_REF is not set\n# CONFIG_DEBUG_RODATA_TEST is not set\nCONFIG_ARCH_HAS_DEBUG_WX=y\n# CONFIG_DEBUG_WX is not set\nCONFIG_ARCH_HAS_PTDUMP=y\n# CONFIG_PTDUMP_DEBUGFS is not set\nCONFIG_HAVE_DEBUG_KMEMLEAK=y\n# CONFIG_DEBUG_KMEMLEAK is not set\n# CONFIG_PER_VMA_LOCK_STATS is not set\n# CONFIG_DEBUG_OBJECTS is not set\n# CONFIG_SHRINKER_DEBUG is not set\nCONFIG_DEBUG_STACK_USAGE=y\n# CONFIG_SCHED_STACK_END_CHECK is not set\nCONFIG_ARCH_HAS_DEBUG_VM_PGTABLE=y\n# CONFIG_DEBUG_VFS is not set\n# CONFIG_DEBUG_VM is not set\n# CONFIG_DEBUG_VM_PGTABLE is not set\nCONFIG_ARCH_HAS_DEBUG_VIRTUAL=y\n# CONFIG_DEBUG_VIRTUAL is not set\n# CONFIG_DEBUG_MEMORY_INIT is not set\n# CONFIG_DEBUG_PER_CPU_MAPS is not set\nCONFIG_ARCH_SUPPORTS_KMAP_LOCAL_FORCE_MAP=y\n# CONFIG_DEBUG_KMAP_LOCAL_FORCE_MAP is not set\n# CONFIG_MEM_ALLOC_PROFILING is not set\nCONFIG_HAVE_ARCH_KASAN=y\nCONFIG_HAVE_ARCH_KASAN_VMALLOC=y\nCONFIG_CC_HAS_KASAN_GENERIC=y\nCONFIG_CC_HAS_KASAN_SW_TAGS=y\nCONFIG_CC_HAS_WORKING_NOSANITIZE_ADDRESS=y\n# CONFIG_KASAN is not set\nCONFIG_HAVE_ARCH_KFENCE=y\n# CONFIG_KFENCE is not set\nCONFIG_HAVE_ARCH_KMSAN=y\nCONFIG_HAVE_KMSAN_COMPILER=y\n# CONFIG_KMSAN is not set\n# end of Memory Debugging\n\n# CONFIG_DEBUG_SHIRQ is not set\n\n#\n# Debug Oops, Lockups and Hangs\n#\nCONFIG_PANIC_ON_OOPS=y\nCONFIG_PANIC_TIMEOUT=0\n# CONFIG_SOFTLOCKUP_DETECTOR is not set\nCONFIG_HAVE_HARDLOCKUP_DETECTOR_BUDDY=y\n# CONFIG_HARDLOCKUP_DETECTOR is not set\nCONFIG_HARDLOCKUP_CHECK_TIMESTAMP=y\n# CONFIG_DETECT_HUNG_TASK is not set\n# CONFIG_WQ_WATCHDOG is not set\n# CONFIG_WQ_CPU_INTENSIVE_REPORT is not set\n# CONFIG_TEST_LOCKUP is not set\n# end of Debug Oops, Lockups and Hangs\n\n#\n# Scheduler Debugging\n#\nCONFIG_SCHED_INFO=y\nCONFIG_SCHEDSTATS=y\n# end of Scheduler Debugging\n\n#\n# Lock Debugging (spinlocks, mutexes, etc...)\n#\nCONFIG_LOCK_DEBUGGING_SUPPORT=y\n# CONFIG_PROVE_LOCKING is not set\n# CONFIG_LOCK_STAT is not set\n# CONFIG_DEBUG_RT_MUTEXES is not set\n# CONFIG_DEBUG_SPINLOCK is not set\n# CONFIG_DEBUG_MUTEXES is not set\n# CONFIG_DEBUG_WW_MUTEX_SLOWPATH is not set\n# CONFIG_DEBUG_RWSEMS is not set\n# CONFIG_DEBUG_LOCK_ALLOC is not set\n# CONFIG_DEBUG_ATOMIC_SLEEP is not set\n# CONFIG_DEBUG_LOCKING_API_SELFTESTS is not set\n# CONFIG_LOCK_TORTURE_TEST is not set\n# CONFIG_WW_MUTEX_SELFTEST is not set\n# CONFIG_SCF_TORTURE_TEST is not set\n# CONFIG_CSD_LOCK_WAIT_DEBUG is not set\n# end of Lock Debugging (spinlocks, mutexes, etc...)\n\n# CONFIG_NMI_CHECK_CPU is not set\n# CONFIG_DEBUG_IRQFLAGS is not set\nCONFIG_STACKTRACE=y\n# CONFIG_WARN_ALL_UNSEEDED_RANDOM is not set\n# CONFIG_DEBUG_KOBJECT is not set\n\n#\n# Debug kernel data structures\n#\n# CONFIG_DEBUG_LIST is not set\n# CONFIG_DEBUG_PLIST is not set\n# CONFIG_DEBUG_SG is not set\n# CONFIG_DEBUG_NOTIFIERS is not set\n# CONFIG_DEBUG_MAPLE_TREE is not set\n# end of Debug kernel data structures\n\n#\n# RCU Debugging\n#\n# CONFIG_RCU_SCALE_TEST is not set\n# CONFIG_RCU_TORTURE_TEST is not set\n# CONFIG_RCU_REF_SCALE_TEST is not set\nCONFIG_RCU_CPU_STALL_TIMEOUT=21\nCONFIG_RCU_EXP_CPU_STALL_TIMEOUT=0\n# CONFIG_RCU_CPU_STALL_CPUTIME is not set\nCONFIG_RCU_TRACE=y\n# CONFIG_RCU_EQS_DEBUG is not set\n# end of RCU Debugging\n\n# CONFIG_DEBUG_WQ_FORCE_RR_CPU is not set\n# CONFIG_CPU_HOTPLUG_STATE_CONTROL is not set\n# CONFIG_LATENCYTOP is not set\n# CONFIG_DEBUG_CGROUP_REF is not set\nCONFIG_USER_STACKTRACE_SUPPORT=y\nCONFIG_NOP_TRACER=y\nCONFIG_HAVE_RETHOOK=y\nCONFIG_RETHOOK=y\nCONFIG_HAVE_FUNCTION_TRACER=y\nCONFIG_HAVE_FUNCTION_GRAPH_TRACER=y\nCONFIG_HAVE_FUNCTION_GRAPH_FREGS=y\nCONFIG_HAVE_FTRACE_GRAPH_FUNC=y\nCONFIG_HAVE_DYNAMIC_FTRACE=y\nCONFIG_HAVE_DYNAMIC_FTRACE_WITH_REGS=y\nCONFIG_HAVE_DYNAMIC_FTRACE_WITH_DIRECT_CALLS=y\nCONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS=y\nCONFIG_HAVE_FTRACE_REGS_HAVING_PT_REGS=y\nCONFIG_HAVE_DYNAMIC_FTRACE_NO_PATCHABLE=y\nCONFIG_HAVE_DYNAMIC_FTRACE_WITH_JMP=y\nCONFIG_HAVE_SYSCALL_TRACEPOINTS=y\nCONFIG_HAVE_FENTRY=y\nCONFIG_HAVE_OBJTOOL_MCOUNT=y\nCONFIG_HAVE_OBJTOOL_NOP_MCOUNT=y\nCONFIG_HAVE_C_RECORDMCOUNT=y\nCONFIG_HAVE_BUILDTIME_MCOUNT_SORT=y\nCONFIG_BUILDTIME_MCOUNT_SORT=y\nCONFIG_TRACE_CLOCK=y\nCONFIG_RING_BUFFER=y\nCONFIG_EVENT_TRACING=y\nCONFIG_CONTEXT_SWITCH_TRACER=y\nCONFIG_TRACING=y\nCONFIG_GENERIC_TRACER=y\nCONFIG_TRACING_SUPPORT=y\nCONFIG_FTRACE=y\nCONFIG_TRACEFS_AUTOMOUNT_DEPRECATED=y\n# CONFIG_BOOTTIME_TRACING is not set\nCONFIG_FUNCTION_TRACER=y\nCONFIG_FUNCTION_GRAPH_TRACER=y\nCONFIG_FUNCTION_GRAPH_RETVAL=y\nCONFIG_FUNCTION_GRAPH_RETADDR=y\nCONFIG_FUNCTION_TRACE_ARGS=y\nCONFIG_DYNAMIC_FTRACE=y\nCONFIG_DYNAMIC_FTRACE_WITH_REGS=y\nCONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS=y\nCONFIG_DYNAMIC_FTRACE_WITH_ARGS=y\nCONFIG_DYNAMIC_FTRACE_WITH_JMP=y\nCONFIG_FUNCTION_SELF_TRACING=y\nCONFIG_FPROBE=y\n# CONFIG_FUNCTION_PROFILER is not set\n# CONFIG_STACK_TRACER is not set\n# CONFIG_IRQSOFF_TRACER is not set\n# CONFIG_SCHED_TRACER is not set\n# CONFIG_HWLAT_TRACER is not set\n# CONFIG_OSNOISE_TRACER is not set\n# CONFIG_TIMERLAT_TRACER is not set\n# CONFIG_MMIOTRACE is not set\nCONFIG_FTRACE_SYSCALLS=y\nCONFIG_TRACE_SYSCALL_BUF_SIZE_DEFAULT=63\n# CONFIG_TRACER_SNAPSHOT is not set\nCONFIG_BRANCH_PROFILE_NONE=y\n# CONFIG_PROFILE_ANNOTATED_BRANCHES is not set\n# CONFIG_PROFILE_ALL_BRANCHES is not set\nCONFIG_BLK_DEV_IO_TRACE=y\nCONFIG_FPROBE_EVENTS=y\nCONFIG_PROBE_EVENTS_BTF_ARGS=y\nCONFIG_KPROBE_EVENTS=y\n# CONFIG_KPROBE_EVENTS_ON_NOTRACE is not set\nCONFIG_UPROBE_EVENTS=y\nCONFIG_EPROBE_EVENTS=y\nCONFIG_BPF_EVENTS=y\nCONFIG_DYNAMIC_EVENTS=y\nCONFIG_PROBE_EVENTS=y\nCONFIG_BPF_KPROBE_OVERRIDE=y\nCONFIG_FTRACE_MCOUNT_USE_OBJTOOL=y\n# CONFIG_SYNTH_EVENTS is not set\n# CONFIG_USER_EVENTS is not set\n# CONFIG_HIST_TRIGGERS is not set\n# CONFIG_TRACE_EVENT_INJECT is not set\n# CONFIG_TRACEPOINT_BENCHMARK is not set\n# CONFIG_RING_BUFFER_BENCHMARK is not set\n# CONFIG_TRACE_EVAL_MAP_FILE is not set\n# CONFIG_FTRACE_RECORD_RECURSION is not set\n# CONFIG_FTRACE_VALIDATE_RCU_IS_WATCHING is not set\n# CONFIG_FTRACE_STARTUP_TEST is not set\n# CONFIG_FTRACE_SORT_STARTUP_TEST is not set\n# CONFIG_RING_BUFFER_STARTUP_TEST is not set\n# CONFIG_RING_BUFFER_VALIDATE_TIME_DELTAS is not set\n# CONFIG_PREEMPTIRQ_DELAY_TEST is not set\n# CONFIG_KPROBE_EVENT_GEN_TEST is not set\n# CONFIG_RV is not set\nCONFIG_PROVIDE_OHCI1394_DMA_INIT=y\nCONFIG_SAMPLES=y\n# CONFIG_SAMPLE_AUXDISPLAY is not set\n# CONFIG_SAMPLE_TRACE_EVENTS is not set\n# CONFIG_SAMPLE_TRACE_CUSTOM_EVENTS is not set\n# CONFIG_SAMPLE_TRACE_PRINTK is not set\n# CONFIG_SAMPLE_FTRACE_DIRECT is not set\n# CONFIG_SAMPLE_FTRACE_DIRECT_MULTI is not set\n# CONFIG_SAMPLE_FTRACE_OPS is not set\n# CONFIG_SAMPLE_TRACE_ARRAY is not set\n# CONFIG_SAMPLE_KOBJECT is not set\nCONFIG_SAMPLE_KPROBES=m\nCONFIG_SAMPLE_KRETPROBES=m\n# CONFIG_SAMPLE_HW_BREAKPOINT is not set\n# CONFIG_SAMPLE_FPROBE is not set\n# CONFIG_SAMPLE_KFIFO is not set\n# CONFIG_SAMPLE_CONFIGFS is not set\n# CONFIG_SAMPLE_CONNECTOR is not set\n# CONFIG_SAMPLE_FANOTIFY_ERROR is not set\n# CONFIG_SAMPLE_HIDRAW is not set\n# CONFIG_SAMPLE_LANDLOCK is not set\n# CONFIG_SAMPLE_PIDFD is not set\n# CONFIG_SAMPLE_SECCOMP is not set\n# CONFIG_SAMPLE_TIMER is not set\n# CONFIG_SAMPLE_TSM_MR is not set\n# CONFIG_SAMPLE_UHID is not set\n# CONFIG_SAMPLE_VFIO_MDEV_MDPY_FB is not set\n# CONFIG_SAMPLE_ANDROID_BINDERFS is not set\n# CONFIG_SAMPLE_VFS is not set\n# CONFIG_SAMPLE_TPS6594_PFSM is not set\n# CONFIG_SAMPLE_WATCHDOG is not set\n# CONFIG_SAMPLE_WATCH_QUEUE is not set\n# CONFIG_SAMPLE_CGROUP is not set\n# CONFIG_SAMPLE_CHECK_EXEC is not set\n\n#\n# DAMON Samples\n#\n# end of DAMON Samples\n\nCONFIG_HAVE_SAMPLE_FTRACE_DIRECT=y\nCONFIG_HAVE_SAMPLE_FTRACE_DIRECT_MULTI=y\nCONFIG_ARCH_HAS_DEVMEM_IS_ALLOWED=y\nCONFIG_STRICT_DEVMEM=y\n# CONFIG_IO_STRICT_DEVMEM is not set\n\n#\n# x86 Debugging\n#\nCONFIG_EARLY_PRINTK_USB=y\nCONFIG_X86_VERBOSE_BOOTUP=y\nCONFIG_EARLY_PRINTK=y\nCONFIG_EARLY_PRINTK_DBGP=y\n# CONFIG_EARLY_PRINTK_USB_XDBC is not set\n# CONFIG_EFI_PGT_DUMP is not set\n# CONFIG_DEBUG_TLBFLUSH is not set\nCONFIG_HAVE_MMIOTRACE_SUPPORT=y\n# CONFIG_X86_DECODER_SELFTEST is not set\nCONFIG_IO_DELAY_0X80=y\n# CONFIG_IO_DELAY_0XED is not set\n# CONFIG_IO_DELAY_UDELAY is not set\n# CONFIG_IO_DELAY_NONE is not set\nCONFIG_DEBUG_BOOT_PARAMS=y\n# CONFIG_CPA_DEBUG is not set\n# CONFIG_DEBUG_ENTRY is not set\n# CONFIG_DEBUG_NMI_SELFTEST is not set\nCONFIG_X86_DEBUG_FPU=y\n# CONFIG_PUNIT_ATOM_DEBUG is not set\nCONFIG_UNWINDER_ORC=y\n# CONFIG_UNWINDER_FRAME_POINTER is not set\n# end of x86 Debugging\n\n#\n# Kernel Testing and Coverage\n#\n# CONFIG_KUNIT is not set\n# CONFIG_NOTIFIER_ERROR_INJECTION is not set\nCONFIG_FUNCTION_ERROR_INJECTION=y\n# CONFIG_FAULT_INJECTION is not set\nCONFIG_ARCH_HAS_KCOV=y\n# CONFIG_KCOV is not set\nCONFIG_RUNTIME_TESTING_MENU=y\n# CONFIG_TEST_DHRY is not set\n# CONFIG_LKDTM is not set\n# CONFIG_TEST_MIN_HEAP is not set\n# CONFIG_TEST_DIV64 is not set\n# CONFIG_TEST_MULDIV64 is not set\n# CONFIG_BACKTRACE_SELF_TEST is not set\n# CONFIG_TEST_REF_TRACKER is not set\n# CONFIG_RBTREE_TEST is not set\n# CONFIG_REED_SOLOMON_TEST is not set\n# CONFIG_INTERVAL_TREE_TEST is not set\n# CONFIG_PERCPU_TEST is not set\n# CONFIG_ATOMIC64_SELFTEST is not set\n# CONFIG_TEST_HEXDUMP is not set\n# CONFIG_TEST_KSTRTOX is not set\n# CONFIG_TEST_BITMAP is not set\n# CONFIG_TEST_UUID is not set\n# CONFIG_TEST_XARRAY is not set\n# CONFIG_TEST_MAPLE_TREE is not set\n# CONFIG_TEST_RHASHTABLE is not set\n# CONFIG_TEST_IDA is not set\n# CONFIG_TEST_LKM is not set\n# CONFIG_TEST_BITOPS is not set\n# CONFIG_TEST_VMALLOC is not set\n# CONFIG_TEST_BPF is not set\n# CONFIG_FIND_BIT_BENCHMARK is not set\n# CONFIG_TEST_FIRMWARE is not set\n# CONFIG_TEST_SYSCTL is not set\n# CONFIG_TEST_UDELAY is not set\n# CONFIG_TEST_STATIC_KEYS is not set\n# CONFIG_TEST_KMOD is not set\n# CONFIG_TEST_KALLSYMS is not set\n# CONFIG_TEST_MEMCAT_P is not set\n# CONFIG_TEST_MEMINIT is not set\n# CONFIG_TEST_FREE_PAGES is not set\n# CONFIG_TEST_FPU is not set\n# CONFIG_TEST_CLOCKSOURCE_WATCHDOG is not set\n# CONFIG_TEST_OBJPOOL is not set\nCONFIG_ARCH_USE_MEMTEST=y\n# CONFIG_MEMTEST is not set\n# end of Kernel Testing and Coverage\n\n#\n# Rust hacking\n#\n# end of Rust hacking\n# end of Kernel hacking\n\nCONFIG_IO_URING_ZCRX=y\n"
  },
  {
    "path": "scripts/q-script/nix-q",
    "content": "#!/usr/bin/env bash\n# based on: https://github.com/fomichev/dotfiles/blob/master/bin/q\n\nusage() {\n\techo \"q [options] [path to bzImage] [script]\"\n\techo\n\techo \"Run it from the kernel directory (make sure .config is there)\"\n\techo\n\techo \"options:\"\n\techo \"    m - run depmod and modprobe\"\n\techo \"    c - pass extra kernel cmdline options\"\n\techo \"    s - start SSH server\"\n\texit 1\n}\n\n# This function is called _BEFORE_ QEMU starts (on host).\nhost() {\n\tlocal kernel=\"$1\"\n\tshift\n\n\tif [ -z \"$kernel\" ]; then\n\t\tif [ -e \"arch/x86/boot/bzImage\" ]; then\n\t\t\tkernel=\"arch/x86/boot/bzImage\"\n\t\tfi\n\t\t[ -n \"$kernel\" ] || usage\n\tfi\n\t[ -e \".config\" ] || usage\n\n\tlocal cmdline\n\n\tlocal fs\n\tfs+=\" -nodefaults\"\n\tfs+=\" -fsdev local,multidevs=remap,id=vfs1,path=/,security_model=none,readonly=on\"\n\tfs+=\" -fsdev local,multidevs=remap,id=vfs2,path=$(pwd),security_model=none\"\n\tfs+=\" -device virtio-9p-pci,fsdev=vfs1,mount_tag=/dev/root\"\n\tfs+=\" -device virtio-9p-pci,fsdev=vfs2,mount_tag=/dev/kernel\"\n\n\tlocal console\n\tconsole+=\" -display none\"\n\tconsole+=\" -serial mon:stdio\"\n\tconsole+=\" -serial tcp::1235,server,nowait\"\n\n\tcmdline+=\" earlyprintk=serial,ttyS0,115200\"\n\tcmdline+=\" console=ttyS0,115200\"\n\tcmdline+=\" kgdboc=ttyS1,115200\"\n\n\tlocal net\n\tif [ \"$SSH\" = \"y\" ]; then\n\t\tnet+=\" -netdev user,id=virtual,hostfwd=tcp:127.0.0.1:52222-:22,hostfwd=tcp::11211-:11211,hostfwd=udp::11211-:11211\"\n\telse\n\t\tnet+=\" -netdev user,id=virtual\"\n\tfi\n\tnet+=\" -device virtio-net-pci,netdev=virtual\"\n\n\tlocal opts\n\t[ \"$MODULES\" = \"y\" ] && opts+=\" -m\"\n\t[ \"$SSH\" = \"y\" ] && opts+=\" -s\"\n\n\tcmdline+=\" rootfstype=9p\"\n\tcmdline+=\" rootflags=version=9p2000.L,trans=virtio,msize=104857600,access=any\"\n\tcmdline+=\" ro\"\n\tcmdline+=\" nokaslr\"\n\tcmdline+=\" $CMDLINE\"\n\tcmdline+=\" init=/usr/bin/env sh -- -c \\\"$(realpath $0) -g $opts -H $HOME -k '$(pwd)' -a '$*'\\\"\"\n\n\tqemu-system-x86_64 \\\n\t\t-nodefaults \\\n\t\t-no-reboot \\\n\t\t-machine accel=kvm:tcg \\\n\t\t-device i6300esb \\\n\t\t-device virtio-rng-pci \\\n\t\t-cpu host \\\n\t\t-smp $NRCPU \\\n\t\t-m $MEMORY \\\n\t\t$fs \\\n\t\t$console \\\n\t\t$net \\\n\t\t$QEMUARG \\\n\t\t-kernel \"$kernel\" \\\n\t\t-append \"$cmdline\" -s\n\n\t# qemu-system-x86_64 \\\n\t# \t-nodefaults \\\n\t# \t-d int \\\n\t# \t-machine accel=tcg \\\n\t# \t-watchdog i6300esb \\\n\t# \t-device virtio-rng-pci \\\n\t# \t-cpu max \\\n\t# \t-smp $NRCPU \\\n\t# \t-m $MEMORY \\\n\t# \t$fs \\\n\t# \t$console \\\n\t# \t$net \\\n\t# \t$QEMUARG \\\n\t# \t-kernel \"$kernel\" \\\n\t# \t-append \"$cmdline\" -s\n}\n\nsay() {\n\ttrap 'tput sgr0' 2 #SIGINT\n\ttput setaf 2\n\techo \">\" \"$@\"\n\ttput sgr0\n}\n\n# This function is called _AFTER_ QEMU starts (on guest).\nguest() {\n\texport PATH=/bin:/sbin:/usr/bin:/usr/sbin\n\texport PATH=$HOME/.nix-profile/bin:$PATH\n\n\tif [[ -f \"$KERNEL/nix_path\" ]]; then\n\t\tNEW_PATHS=$(/usr/bin/env bat \"$KERNEL/nix_path\")\n\t\texport PATH=\"${NEW_PATHS}:${PATH}\"\n\tfi\n\n\tsay pivot root\n\n\tmount -n -t proc -o nosuid,noexec,nodev proc /proc/\n\n\tmount -n -t tmpfs tmpfs /tmp\n\tmkdir -p /tmp/rootdir-overlay/{lower,upper,work,mnt}\n\tmount --bind / /tmp/rootdir-overlay/lower\n\tmount -t overlay overlay -o lowerdir=/tmp/rootdir-overlay/lower,upperdir=/tmp/rootdir-overlay/upper,workdir=/tmp/rootdir-overlay/work /tmp/rootdir-overlay/mnt\n\tpivot_root /tmp/rootdir-overlay/mnt{,/mnt}\n\tcd /\n\n\tsay early setup\n\n\tmount -n -t sysfs -o nosuid,noexec,nodev sys /sys/\n\n\tmount -n -t tmpfs tmpfs /tmp\n\tmount -n -t tmpfs tmpfs /var/log\n\tmount -n -t tmpfs tmpfs /run\n\n\trm -f /etc/fstab\n\ttouch /etc/fstab\n\n\tmount -n -t proc -o nosuid,noexec,nodev proc /proc/\n\tmount -n -t configfs configfs /sys/kernel/config\n\tmount -n -t debugfs debugfs /sys/kernel/debug\n\tmount -n -t securityfs security /sys/kernel/security\n\tmount -n -t devtmpfs -o mode=0755,nosuid,noexec devtmpfs /dev\n\n\tmkdir -p -m 0755 /dev/shm /dev/pts\n\tmount -n -t devpts -o gid=tty,mode=620,noexec,nosuid devpts /dev/pts\n\tmount -n -t tmpfs -o mode=1777,nosuid,nodev tmpfs /dev/shm\n\n\tln -s /proc/self/fd /dev/fd\n\n\tmount --move /mnt /tmp\n\tmount -n -t tmpfs tmpfs /mnt\n\tmkdir /mnt/base-root\n\tmount --move /tmp /mnt/base-root\n\n\tlocal kver=\"`uname -r`\"\n\tlocal mods=\"$(find /sys/devices -type f -name modalias -print0 | xargs -0 cat | sort | uniq)\"\n\tlocal mods_nr=$(echo \"$mods\" | wc -w)\n\n\tsay modules /lib/modules/$kver $mods_nr modules\n\tmount -n -t 9p -o version=9p2000.L,trans=virtio,msize=104857600 /dev/kernel $KERNEL\n        # Create lib/modules if on NixOS\n        mkdir -p /lib/modules\n\tmount -n -t tmpfs tmpfs /lib/modules\n\tmkdir \"/lib/modules/$kver\"\n\tln -s $KERNEL \"/lib/modules/$kver/source\"\n\tln -s $KERNEL \"/lib/modules/$kver/build\"\n\tln -s $KERNEL \"/lib/modules/$kver/kernel\"\n\n\tcp $KERNEL/modules.builtin \"/lib/modules/$kver/modules.builtin\"\n\tcp $KERNEL/modules.builtin.modinfo \"/lib/modules/$kver/modules.builtin.modinfo\"\n\tcp $KERNEL/modules.order \"/lib/modules/$kver/modules.order\"\n\n\t# make sure config points to the right place\n\tmount -n -t tmpfs tmpfs /boot\n\tln -s $KERNEL/.config /boot/config-$kver\n\n\tif [ \"$MODULES\" = \"y\" ]; then\n\t\tif [ ! -e $KERNEL/modules.dep.bin ]; then\n\t\t\tsay modules.dep.bin not found, running depmod, may take awhile\n\t\t\tdepmod -a 2>/dev/null\n\t\tfi\n\t\tmodprobe -q -a -- $mods\n\tfi\n\n\tsay networking\n\n\thostname q\n\trm -f /etc/hostname\n\techo q > /etc/hostname\n\n\tip link set dev lo up\n\n\trm -f /etc/resolv.conf\n\techo \"nameserver 8.8.8.8\" > /etc/resolv.conf\n\n\tlocal dev=$(ls -d /sys/bus/virtio/drivers/virtio_net/virtio* |sort -g |head -n1)\n\tlocal iface=$(ls $dev/net)\n\tsay dhcp on iface $iface\n\tip link set dev $iface up\n\t# busybox udhcpc -i $iface -p /run/udhcpc \\\n\t# \t-s /usr/share/udhcpc/default.script -q -t 1 -n -f\n\n\tsay setup cgroups\n\tsysctl -q kernel.allow_bpf_attach_netcg=0 &>/dev/null\n\tmount -t cgroup2 none /sys/fs/cgroup\n\n\tsay setup bpf\n\tsysctl -q net.core.bpf_jit_enable=1\n\tsysctl -q net.core.bpf_jit_kallsyms=1\n\tsysctl -q net.core.bpf_jit_harden=0\n\tmount -t bpf bpffs /sys/fs/bpf\n\tulimit -l unlimited &>/dev/null # EINVAL when loading more than 3 bpf programs\n\tulimit -n 819200 &>/dev/null\n\tulimit -a &>/dev/null\n\n\tsay root passwd\n\trm -f /etc/{shadow,gshadow}\n\tpwconv\n\tgrpconv\n\n\tmount --bind / /mnt\n\tusermod -R /mnt -d \"$HOME\" root\n\tumount /mnt\n\n  # For system cannot get ip addr by udhcpc\n  local ip_address=$(ip -4 addr show $iface | grep -oP '(?<=inet\\s)\\d+(\\.\\d+){3}')\n  local default_route=$(ip route | grep default)\n  if [[ -z \"$ip_address\" ]]; then\n      ip a add 10.0.2.15/24 dev eth0 \n  fi\n  if [[ -z \"$default_route\" ]]; then\n    ip route add default via 10.0.2.2\n  fi\n\n\tif [ \"$SSH\" = \"y\" ]; then\n\t\tsay setup sshd: '$ ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@localhost -p 52222'\n\t\tmask-dir () {\n\t\t\ttouch \"$1\"\n\t\t\tsetfattr -n trusted.overlay.opaque -v y /mnt/base-root/tmp/rootdir-overlay/upper/\"$1\"\n\t\t\tmount -o remount /\n\t\t}\n\t\tmask-dir /etc/ssh/\n\n\t\tcat << 'EOF' > /etc/pam.d/sshd\naccount sufficient pam_permit.so\nauth sufficient pam_permit.so\npassword sufficient pam_permit.so\nsession sufficient pam_permit.so\nEOF\n\n\t\tssh-keygen -A\n    mkdir -p /run/sshd\n\t\t`which sshd` -p 22 -o UsePAM=yes -o PermitRootLogin=yes -f /dev/null -E /var/log/sshd\n\tfi\n\n\tsay root environment\n\ncat << EOF >> $HOME/.profile\nexport KERNEL=$KERNEL\n\nexport PATH=\\$HOME/local/bin:\\$PATH\nexport PATH=\\$KERNEL/tools/bpf/bpftool:\\$PATH\nexport PATH=\\$KERNEL/tools/perf:\\$PATH\nexport PATH=\\$HOME/.nix-profile/bin:\\$PATH\nEOF\n\n\tcat << EOF >> $HOME/.bashrc\nmask-dir () {\n\ttouch \"\\$1\"\n\tsetfattr -n trusted.overlay.opaque -v y /mnt/base-root/tmp/rootdir-overlay/upper/\"\\$1\"\n\tmount -o remount /\n}\n\nsource $KERNEL/tools/bpf/bpftool/bash-completion/bpftool\n\neval \\$(resize)\nEOF\n\n\tcd $KERNEL\n\n\tif [ -n \"$ARGS\" ]; then\n\t\tsay non-interactive bash script\n\t\tsetsid bash -l -c \"$ARGS\"\n\t\tif [ ! $? -eq 0 ]; then\n\t\t\tsay script failed, starting interactive console\n\t\t\tsetsid bash -l 0<>\"/dev/ttyS0\" 1>&0 2>&0\n\t\tfi\n\telse\n\t\tsay interactive bash\n\t\tsetsid bash -l 0<>\"/dev/ttyS0\" 1>&0 2>&0\n\tfi\n\n\techo\n\tsay poweroff\n\tpoweroff -f\n\techo o > /proc/sysrq-trigger\n\tsleep 30\n}\n\nGUEST=n\nMODULES=n\nSSH=n\nCMDLINE=\"\"\nQEMUARG=\"\"\n\nNRCPU=4\nMEMORY=8192\n\nwhile getopts \"hgmsk:c:a:H:N:M:q:\" opt; do\n\tcase $opt in\n\t\th) usage ;;\n\t\tg) GUEST=y ;;\n\t\tm) MODULES=y ;;\n\t\ts) SSH=y ;;\n\t\tk) KERNEL=\"$OPTARG\" ;;\n\t\tc) CMDLINE=\"$OPTARG\" ;;\n\t\ta) ARGS=\"$OPTARG\" ;;\n\t\tH) export HOME=$OPTARG ;;\n\t\tM) MEMORY=\"$OPTARG\" ;;\n\t\tN) NRCPU=\"$OPTARG\" ;;\n\t\tq) QEMUARG=\"$OPTARG\" ;;\n\tesac\ndone\nshift $((OPTIND -1))\n\n[ \"$GUEST\" = \"y\" ] && guest \"$@\" || host \"$@\"\n"
  },
  {
    "path": "scripts/q-script/sanity-test-q",
    "content": "#!/bin/bash\n# based on: https://github.com/fomichev/dotfiles/blob/master/bin/q\n\n# External variables, users can override:\n# {{{\nSSH_PORT=${SSH_PORT:-52222}\n\nNRCPU=${NRCPU:-2}\nMEMORY=${MEMORY:-4096}\nTAP_QUEUES=${TAP_QUEUES:-$NRCPU}\nTAP_MQ=${TAP_MQ:-true}\n\nV4_ADDR=${V4_ADDR:-\"10.0.2.15\"} # dhcp by default\nV4_PREFIX=${V4_PREFIX:-\"24\"}    # dhcp by default\nV4_ROUTE=${V4_ROUTE:-\"10.0.2.2\"}\nV6_ADDR=${V6_ADDR:-\"2002:ad6:c2c4::1\"}\nV6_PREFIX=${V6_PREFIX:-128}\n\nHOST=${HOST:-q}\n# }}}\n\n# Internal variables:\n# {{{\nDIR_Q=\"$(dirname $0)\"\nDIR_EXPORT=/media\nDIR_ROOT=${DIR_ROOT:-/}\nDIR_KERNEL=${DIR_KERNEL:-}\nIMAGE=${IMAGE:-}\nIMAGE_PART=\"sda1\"\nIMAGE_INIT=\"/sbin/init.real\"\nSCRIPT=${SCRIPT:-}\nENVIRON_ARG=${ENVIRON_ARG:-}\n\nGDB=${GDB:-false}\nGUEST=${GUEST:-false}\nMODULES=${MODULES:-false}\nTTY=${TTY:-ttyS0}\nSSH=${SSH:-false}\nFWD_PORT=${FWD_PORT:-}\nNET_USER=${NET_USER:-true}\nNET_TAP=${NET_TAP:-false}\nNET_VHOST=${NET_VHOST:-false}\n# }}}\n\nusage() {\n\tif [[ -n \"$*\" ]]; then\n\t\techo \"error: $@\"\n\t\techo\n\tfi\n\n\techo \"q [options] [path to bzImage]\"\n\techo\n\techo \"Run it from the kernel directory (make sure .config is there)\"\n\techo\n\techo \"options:\"\n\techo \"    i - use specified disk image instead of rootfs\"\n\techo \"    g - support attaching with gdb\"\n\techo \"    m - run depmod and modprobe\"\n\techo \"    c - pass extra kernel cmdline options\"\n\techo \"    d - start SSH server\"\n\techo \"    s - run script instead of interactive bash\"\n\techo \"    2 - disable cgroup v1, run only v2\"\n\techo \"    f - forward given localhost port (comma-separated list)\"\n\techo \"    n - networking mode (user,tap,vhost)\"\n\texit 1\n}\n\nfixup() {\n\tlocal stage=\"$1\"\n\n\tif [[ -z \"$IMAGE_FIXUP\" ]]; then\n\t\treturn\n\tfi\n\n\tsay FIXUP $stage\n\t${stage}_fixup\n}\n\n# This function is called _BEFORE_ QEMU starts (on host).\nhost() {\n\tlocal kernel=\"$1\"\n\n\t[[ -e \".config\" ]] || usage\n\n\tlocal cmdline\n\n\tlocal fs\n\tfs+=\" -fsdev local,multidevs=remap,id=vfs1,path=$DIR_ROOT,security_model=none,readonly=on\"\n\tfs+=\" -fsdev local,id=vfs2,path=$(pwd),security_model=none\"\n\t# fs+=\" -fsdev local,id=vfs3,path=$DIR_EXPORT,security_model=none\"\n\tfs+=\" -fsdev local,id=vfs4,path=$DIR_Q,security_model=none,readonly=on\"\n\tfs+=\" -device virtio-9p-pci,fsdev=vfs1,mount_tag=/dev/root\"\n\tfs+=\" -device virtio-9p-pci,fsdev=vfs2,mount_tag=/dev/kernel\"\n\t# fs+=\" -device virtio-9p-pci,fsdev=vfs3,mount_tag=$DIR_EXPORT\"\n\tfs+=\" -device virtio-9p-pci,fsdev=vfs4,mount_tag=/tmp/dir_q\"\n\n\tlocal console\n\tconsole+=\" -display none\"\n\tconsole+=\" -serial mon:stdio\"\n\n\tcmdline+=\" earlyprintk=serial,ttyS0,115200\"\n\tif [[ \"${ARCH}\" != \"arm64\" ]]; then\n\t\tcmdline+=\" console=ttyS0\"\n\t\tcmdline+=\" kgdboc=ttyS1,115200\"\n\tfi\n\tcmdline+=\" oops=panic retbleed=off\"\n\n\tlocal net\n\n\tif $NET_USER; then\n\t\tnet+=\" -netdev user,id=virtual\"\n\n\t\tif $SSH; then\n\t\t\tnet+=\",hostfwd=tcp:127.0.0.1:$SSH_PORT-:22\"\n\t\tfi\n\t\tif [[ ! -z \"$FWD_PORT\" ]]; then\n\t\t\tfor p in $(echo \"$FWD_PORT\" | tr ',' ' '); do\n\t\t\t\tnet+=\",hostfwd=tcp::${p}-:$p\"\n\t\t\tdone\n\t\tfi\n\n\t\tnet+=\" -device virtio-net-pci,netdev=virtual\"\n\tfi\n\n\tif $NET_TAP; then\n\t\tlocal dev=\"qtap1\"\n\t\tif $TAP_MQ; then\n\t\t\tdev=\"qtap0\"\n\t\tfi\n\n\t\tlocal vhost=\"\"\n\n\t\tif $NET_VHOST; then\n\t\t\tvhost=\",vhost=on\"\n\t\tfi\n\n\t\tnet+=\" -netdev tap,id=virtual,ifname=$dev,script=no$vhost\"\n\t\tif $TAP_MQ; then\n\t\t\tnet+=\",queues=${TAP_QUEUES}\"\n\t\tfi\n\n\t\tnet+=\" -device virtio-net-pci,netdev=virtual\"\n\t\tif $TAP_MQ; then\n\t\t\tnet+=\",mq=on\"\n\t\tfi\n\tfi\n\n\tcmdline+=\" $CMDLINE\"\n\tcmdline+=\" rootfstype=9p\"\n\tcmdline+=\" rootflags=version=9p2000.L,trans=virtio,access=any\"\n\tcmdline+=\" ro\"\n\tcmdline+=\" nokaslr\"\n\n\tlocal gdb\n\t$GDB && gdb+=\" -s\"\n\n\tif [[ ! -z \"$IMAGE\" ]]; then\n\t\tfs+=\" -drive format=raw,file=$IMAGE\"\n\tfi\n\n\tlocal accel\n\tif [[ \"$(uname -m)\" = \"${ARCH}\" ]]; then\n\t\tif [[ -e /dev/kvm ]]; then\n\t\t\taccel+=\" -machine accel=kvm:tcg\"\n\t\t\taccel+=\" -enable-kvm\"\n\t\tfi\n\tfi\n\n\tfixup host\n\n\tlocal cpu\n\tlocal qemu_flavor=$ARCH\n\tcase \"${ARCH}\" in\n\tx86_64)\n\t\tif [[ \"$(uname -m)\" = \"${ARCH}\" ]]; then\n\t\t\tif [[ -e /dev/kvm ]]; then\n\t\t\t\tcpu=\"host\"\n\t\t\telse\n\t\t\t\tcpu=\"max\"\n\t\t\tfi\n\t\tfi\n\t\t;;\n\tarm64)\n\t\tif [[ \"$(uname -m)\" = \"${ARCH}\" ]]; then\n\t\t\tcpu=\"host\"\n\t\telse\n\t\t\taccel+=\" -machine virt -accel tcg \"\n\t\t\tcpu=\"max\"\n\t\tfi\n\t\tqemu_flavor=aarch64\n\t\tTTY=ttyAMA0\n\t\t;;\n\tesac\n\n\tlocal init\n\t# init+=\"mount -n -t tmpfs tmpfs /tmp\"\n\t# init+=\" && \"\n\t# init+=\"mkdir -p /tmp/dir_q\"\n\t# init+=\" && \"\n\t# init+=\"mount -n -t 9p -o trans=virtio /tmp/dir_q /tmp/dir_q\"\n\t# init+=\" && \"\n\tinit+=\"GUEST='true' \"\n\tinit+=\"IMAGE='$IMAGE' \"\n\tinit+=\"GDB='$GDB' \"\n\tinit+=\"TTY='$TTY' \"\n\tinit+=\"HOSTNAME='$HOSTNAME' \"\n\tinit+=\"HOME='$HOME' \"\n\tinit+=\"DIR_ROOT='$DIR_ROOT' \"\n\tinit+=\"DIR_KERNEL='$(pwd)' \"\n\tinit+=\"MODULES='$MODULES' \"\n\tinit+=\"SSH='$SSH' \"\n\tinit+=\"FWD_PORT='$FWD_PORT' \"\n\tinit+=\"V4_ADDR='$V4_ADDR' \"\n\tinit+=\"V4_PREFIX='$V4_PREFIX' \"\n\tinit+=\"V6_ADDR='$V6_ADDR' \"\n\tinit+=\"V6_PREFIX='$V6_PREFIX' \"\n\tinit+=\"NET_USER='$NET_USER' \"\n\tinit+=\"NET_TAP='$NET_TAP' \"\n\tinit+=\"NET_VHOST='$NET_VHOST' \"\n\tinit+=\"SCRIPT='$SCRIPT' \"\n\tinit+=\"$ENVIRON_ARG \"\n\t# grading script specific\n\tinit+=\"TEST_PATH='$TEST_PATH' \"\n\n\tinit+=\" $(realpath $0) \"\n\n\tcmdline+=\" init=/bin/sh -- -c \\\"$init\\\"\"\n\n\tif [[ -z \"$cpu\" ]]; then\n\t\techo \"unknown cpu for ${ARCH} arch\"\n\t\texit 1\n\tfi\n\n\tqemu-system-${qemu_flavor} \\\n\t\t-nographic \\\n\t\t-no-reboot \\\n\t\t$accel \\\n\t\t-device i6300esb,id=watchdog0 \\\n\t\t-watchdog-action pause \\\n\t\t-device virtio-rng-pci \\\n\t\t-cpu $cpu \\\n\t\t-smp $NRCPU \\\n\t\t-m $MEMORY \\\n\t\t$fs \\\n\t\t$console \\\n\t\t$net \\\n\t\t$gdb \\\n\t\t-kernel \"$kernel\" \\\n\t\t-append \"$cmdline\"\n}\n\nsay() {\n\ttrap 'tput sgr0' 2 #SIGINT\n\t# tput setaf 2\n\tprintf \"\\33[32m\"\n\techo \">\" \"$@\"\n\t# tput sgr0\n\tprintf \"\\33(B\\33[m\"\n}\n\nmask-dir() {\n\tlocal upper_dir=\"/mnt/base-root/tmp/rootdir-overlay/upper/$1\"\n\n\tmkdir -p \"$upper_dir\"\n\tsetfattr -n trusted.overlay.opaque -v y \"$upper_dir\"\n\tmount -o remount /\n}\n\nappend_to_hosts() {\n\tlocal addr=\"$1\"\n\n\tlocal prefix=$(echo \"$HOSTNAME\" | cut -d. -f1)\n\tlocal suffix=$(echo \"$HOSTNAME\" | cut -d. -f2-)\n\n\tif [[ ! -z \"$suffix\" ]]; then\n\t\tsuffix=\".${suffix}\"\n\tfi\n\n\tif ! echo \"$addr\" | grep -q ':'; then\n\t\tprefix=\"${prefix}-v4\"\n\tfi\n\n\techo \"$addr ${prefix}${suffix} ${prefix}\" >>/etc/hosts\n}\n\n# This function is called _AFTER_ QEMU starts (on guest).\nguest() {\n\texport PATH=/bin:/sbin:/usr/bin:/usr/sbin\n\n\tsay pivot root\n\n\tlocal overlay=\"/tmp/rootdir-overlay\"\n\n\tmount -n -t proc -o nosuid,noexec,nodev proc /proc/\n\n\tmount -n -t tmpfs tmpfs /tmp\n\tmkdir -p $overlay/{lower,upper,work,mnt}\n\tmount --bind / $overlay/lower\n\tmount -t overlay overlay -o lowerdir=$overlay/lower,upperdir=$overlay/upper,workdir=$overlay/work $overlay/mnt\n\tpivot_root $overlay/mnt{,/tmp}\n\tcd /\n\tmount -n -t proc -o nosuid,noexec,nodev proc /proc/\n\n\tmount -n -t tmpfs tmpfs /mnt\n\tmkdir /mnt/base-root\n\tmount --move /tmp /mnt/base-root\n\n\tsay early setup\n\n\tmount -n -t sysfs -o nosuid,noexec,nodev sys /sys/\n\n\tmount -n -t tmpfs tmpfs /tmp\n\tmount -n -t tmpfs tmpfs /var/log\n\tmount -n -t tmpfs tmpfs /run\n\n\tif [[ -d /export ]]; then\n\t\tmount -n -t tmpfs tmpfs /export\n\t\tmkdir -p $DIR_EXPORT\n\t\tmount -n -t 9p -o trans=virtio $DIR_EXPORT $DIR_EXPORT\n\telse\n\t\tsay \"$/expor mount point doesn't exist, not mounting $DIR_EXPORT\"\n\tfi\n\n\t>/etc/fstab\n\n\tmount -n -t configfs configfs /sys/kernel/config\n\tmount -n -t debugfs debugfs /sys/kernel/debug\n\tif [[ -d /sys/kernel/security ]]; then\n\t\tmount -n -t securityfs security /sys/kernel/security\n\tfi\n\tmount -n -t devtmpfs -o mode=0755,nosuid,noexec devtmpfs /dev\n\n\tmkdir -p -m 0755 /dev/shm /dev/pts /dev/cgroup\n\tmkdir -p -m 0755 /dev/cgroup/{cpu,cpuset,net} 2>/dev/null\n\tmount -n -t devpts -o gid=tty,mode=620,noexec,nosuid devpts /dev/pts\n\tmount -n -t tmpfs -o mode=1777,nosuid,nodev tmpfs /dev/shm\n\n\tif [[ -d \"$DIR_KERNEL\" ]]; then\n\t\tlocal kver=\"$(uname -r)\"\n\t\tlocal mods=\"$(find /sys/devices -type f -name modalias -print0 | xargs -0 cat | sort | uniq)\"\n\t\tlocal mods_nr=$(echo \"$mods\" | wc -w)\n\n\t\tsay modules /lib/modules/$kver $mods_nr modules\n\t\tmount -n -t 9p -o trans=virtio /dev/kernel \"$DIR_KERNEL\"\n\t\tmount -n -t tmpfs tmpfs /lib/modules\n\t\tmkdir \"/lib/modules/$kver\"\n\t\tln -s \"$DIR_KERNEL\" \"/lib/modules/$kver/source\"\n\t\tln -s \"$DIR_KERNEL\" \"/lib/modules/$kver/build\"\n\t\tln -s \"$DIR_KERNEL\" \"/lib/modules/$kver/kernel\"\n\n\t\tcp \"$DIR_KERNEL/modules.builtin\" \"/lib/modules/$kver/modules.builtin\"\n\t\tcp \"$DIR_KERNEL/modules.order\" \"/lib/modules/$kver/modules.order\"\n\n\t\t# make sure config points to the right place\n\t\tmount -n -t tmpfs tmpfs /boot\n\t\tln -s \"$DIR_KERNEL/.config\" /boot/config-$kver\n\n\t\tif $MODULES; then\n\t\t\tif [[ ! -e \"$DIR_KERNEL/modules.dep.bin\" ]]; then\n\t\t\t\tsay modules.dep.bin not found, running depmod, may take awhile\n\t\t\t\tdepmod -a 2>/dev/null\n\t\t\tfi\n\t\t\tmodprobe -q -a -- $mods\n\t\tfi\n\telse\n\t\tsay \"$DIR_KERNEL mount point doesn't exist, not mounting\"\n\tfi\n\n\tsay networking as $HOSTNAME\n\n\tif [[ -n \"$(command -v hostname)\" ]]; then\n\t\thostname \"$HOSTNAME\"\n\t\techo \"$HOSTNAME\" >/etc/hostname\n\telse\n\t\tsay \"hostname is not found, don't set hostname\"\n\tfi\n\n\tip link set dev lo up\n\n\tif $NET_USER; then\n\t\tif [[ -n \"$(command -v busybox)\" ]]; then\n\t\t\tif [[ -e \"/etc/udhcpc/default.script\" ]]; then\n\t\t\t\tmask-dir /etc/resolvconf/run\n\t\t\t\tmkdir -p /run/resolvconf\n\t\t\t\techo \"nameserver 8.8.8.8\" >/run/resolvconf/resolv.conf\n\n\t\t\t\tlocal dev=$(ls -d /sys/bus/virtio/drivers/virtio_net/virtio* | sort -g | head -n1)\n\t\t\t\tlocal iface=$(ls $dev/net)\n\t\t\t\tsay dhcp on iface $iface\n\t\t\t\tip link set dev $iface up\n\t\t\t\tdhcpcd $iface\n\t\t\t\tbusybox udhcpc -i $iface -p /run/udhcpc \\\n\t\t\t\t\t-s /etc/udhcpc/default.script -q -t 1 -n -f\n\n\t\t\t\tappend_to_hosts \"$v4_addr\"\n\t\t\telse\n\t\t\t\tsay \"busybox is found, but no /etc/udhcpc/default.script, use assigned ip address\"\n\t\t\t\tif [[ ! -z \"$V4_ADDR\" ]]; then\n\t\t\t\t\tmask-dir /etc/resolvconf/run\n\t\t\t\t\tmkdir -p /run/resolvconf\n\t\t\t\t\techo \"nameserver 8.8.8.8\" >/run/resolvconf/resolv.conf\n\n\t\t\t\t\tlocal dev=$(ls -d /sys/bus/virtio/drivers/virtio_net/virtio* | sort -g | head -n1)\n\t\t\t\t\tlocal iface=$(ls $dev/net)\n\t\t\t\t\tip link set dev $iface up\n\t\t\t\t\tip -4 addr add \"${V4_ADDR}/${V4_PREFIX}\" dev $iface\n\t\t\t\t\tip -4 route add default via $V4_ROUTE\n\t\t\t\t\tappend_to_hosts \"$V4_ADDR\"\n\t\t\t\tfi\n\t\t\tfi\n\t\telse\n\t\t\tsay \"busybox is not found, skipping udhcpc\"\n\t\tfi\n\tfi\n\n\tif $NET_TAP; then\n\t\tip link set dev eth0 up\n\tfi\n\n\tif [[ ! -z \"$V6_ADDR\" ]]; then\n\t\tip -6 addr add \"${V6_ADDR}/${V6_PREFIX}\" dev eth0\n\t\tappend_to_hosts \"$V6_ADDR\"\n\tfi\n\n\tif [[ ! -z \"$V4_ADDR\" ]]; then\n\t\tip -4 addr add \"${V4_ADDR}/${V4_PREFIX}\" dev eth0\n\t\tappend_to_hosts \"$V4_ADDR\"\n\tfi\n\n\tif [[ ! -z \"$IMAGE\" ]]; then\n\t\tsay fsck\n\t\tfsck -T -y -v -r \"/dev/$IMAGE_PART\"\n\n\t\tsay mount disk\n\t\tmkdir /mnt/root\n\t\tmount -n \"/dev/$IMAGE_PART\" /mnt/root\n\n\t\tfixup guest_pre_pivot\n\n\t\tsay pivot root\n\t\tpivot_root /mnt/root{,/tmp}\n\t\tcd /\n\n\t\tumount /tmp/{tmp,var/log,run}\n\n\t\tmkdir -p /root/9p-overlay\n\t\tmount --move /tmp /root/9p-overlay\n\t\tmount -n -t tmpfs tmpfs /root/9p-overlay\n\n\t\tfixup guest_post_pivot\n\n\t\tsay exec init\n\t\tmount -n -o remount,ro /\n\t\texec \"$IMAGE_INIT\"\n\tfi\n\n\tsay setup cgroups\n\tmount -t cgroup -o cpu,cpuacct none /dev/cgroup/cpu\n\tmount -t cgroup -o cpuset none /dev/cgroup/cpuset\n\tmount -t cgroup -o net_cls none /dev/cgroup/net &>/dev/null\n\tsysctl -q kernel.allow_bpf_attach_netcg=0 &>/dev/null\n\tmount -t cgroup2 none /sys/fs/cgroup\n\n\tsay setup bpf\n\tsysctl -q net.core.bpf_jit_enable=1\n\tsysctl -q net.core.bpf_jit_kallsyms=1\n\tsysctl -q net.core.bpf_jit_harden=0\n\tmount -t bpf bpffs /sys/fs/bpf\n\tulimit -l unlimited &>/dev/null # EINVAL when loading more than 3 bpf programs\n\tulimit -n 819200 &>/dev/null\n\tulimit -a &>/dev/null\n\n\tif $SSH; then\n\t\tsay setup sshd\n\t\tsay ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@localhost -p $SSH_PORT\n\n\t\tmask-dir /etc/ssh\n\t\tmask-dir /etc/pam.d\n\t\tmkdir -p /var/run/sshd\n\t\tcat <<'EOF' >/etc/pam.d/sshd\naccount sufficient pam_permit.so\nauth sufficient pam_permit.so\npassword sufficient pam_permit.so\nsession sufficient pam_permit.so\nEOF\n\n\t\techo \"root:x:0:0:root:/:/bin/bash\" >/etc/passwd\n\t\techo \"sshd:x:123:65534::/var/run/sshd:/usr/sbin/nologin\" >>/etc/passwd\n\n\t\techo \"root:*:17785:0:99999:7:::\" >/etc/shadow\n\n\t\techo \"\" >/etc/group\n\n\t\tcat $HOME/.ssh/id_rsa.pub >>/etc/ssh/authorized_keys\n\n\t\tssh-keygen -A\n\n\t\t$(which sshd) \\\n\t\t\t-p 22 \\\n\t\t\t-o UsePAM=yes \\\n\t\t\t-o PermitRootLogin=yes \\\n\t\t\t-o AuthorizedKeysFile=/etc/ssh/authorized_keys \\\n\t\t\t-f /dev/null \\\n\t\t\t-E /var/log/sshd\n\tfi\n\n\tif $GDB; then\n\t\tlocal kconfig=$(zcat /proc/config.gz | grep CONFIG_GDB_SCRIPT)\n\t\tif [[ ! \"$kconfig\" = \"CONFIG_GDB_SCRIPTS=y\" ]]; then\n\t\t\tsay requested GDB, but missing CONFIG_GDB_SCRIPTS=y\n\t\tfi\n\tfi\n\n\tsay root environment\n\ttouch /etc/{profile,bash.bashrc}\n\t>/etc/profile\n\t>/etc/bash.bashrc\n\n\tmkdir -pm 0755 /root\n\ttouch /root/.bashrc &>/dev/null\n\ttouch /root/.bash_profile &>/dev/null\n\n\tlocal rcfile=/tmp/.bashrc\n\texport PATH=$HOME/local/bin:$PATH\n\tif [[ -d \"$DIR_KERNEL\" ]]; then\n\t\texport PATH=\"$DIR_KERNEL/tools/bpf/bpftool:$PATH\"\n\t\texport PATH=\"$DIR_KERNEL/tools/perf:$PATH\"\n\tfi\n\texport NO_BASE16=true # hack for my bashrc to disable colors\n\n\tcat <<EOF >$rcfile\nexport DIR_KERNEL=\"$DIR_KERNEL\"\n\nexport PATH=\\$HOME/local/bin:\\$PATH\nexport PATH=\\$DIR_KERNEL/tools/bpf/bpftool:\\$PATH\nexport PATH=\\$DIR_KERNEL/tools/perf:\\$PATH\n\nmask-dir () {\n\tlocal upper_dir=\"/mnt/base-root/tmp/rootdir-overlay/upper/\\$1\"\n\n\tmkdir -p \"\\$upper_dir\"\n\tsetfattr -n trusted.overlay.opaque -v y \"\\$upper_dir\"\n\tmount -o remount /\n}\n\nif [[ -e \"\\$HOME/.bashrc\" ]]; then\n\tsource \\$HOME/.bashrc\nfi\nif [[ -e \"\\$DIR_KERNEL\" ]]; then\n\tsource \"\\$DIR_KERNEL/tools/bpf/bpftool/bash-completion/bpftool\"\nfi\nif [[ -n \"\\$(command -v resize)\" ]]; then\n\tresize &>/dev/null\nfi\nEOF\n\n\tif [[ -d \"$DIR_KERNEL\" ]]; then\n\t\tsource \"$DIR_KERNEL/tools/bpf/bpftool/bash-completion/bpftool\"\n\t\tcd \"$DIR_KERNEL\"\n\tfi\n\n\tSAMPLE_PATH=$(dirname $TEST_PATH)\n\tcd $SAMPLE_PATH\n\techo $TEST_PATH\n\tpwd\n\tpython3 ${TEST_PATH}\n\tcp auto_grade.txt ${DIR_KERNEL}\n\n\tpoweroff -f\n\n\tif [[ -n \"$SCRIPT\" ]]; then\n\t\tsay non-interactive bash script\n\t\tsetsid bash --rcfile $rcfile -c \"$SCRIPT\"\n\t\tif [[ ! $? -eq 0 ]]; then\n\t\t\tsay script failed, starting interactive console\n\t\t\tsetsid bash --rcfile $rcfile 0<>\"/dev/$TTY\" 1>&0 2>&0\n\t\tfi\n\telse\n\t\tsay interactive bash $rcfile\n\t\tsetsid bash --rcfile $rcfile 0<>\"/dev/$TTY\" 1>&0 2>&0\n\tfi\n\n\techo\n\tsay poweroff\n\techo o >/proc/sysrq-trigger\n\tsleep 30\n}\n\nwhile getopts \"2i:dhgms:c:f:t:n\" opt; do\n\tcase $opt in\n\th) usage ;;\n\t2) CMDLINE+=\" cgroup_no_v1=all\" ;;\n\ti) IMAGE=\"$OPTARG\" ;;\n\tg) GDB=true ;;\n\tm) MODULES=true ;;\n\tc) CMDLINE=\"$OPTARG\" ;;\n\td) SSH=true ;;\n\ts) SCRIPT=\"$OPTARG\" ;;\n\tf) FWD_PORT=\"$OPTARG\" ;;\n\tt) TEST_PATH=\"$OPTARG\"  ;;\n\tn)\n\t\tcase \"$OPTARG\" in\n\t\tuser) ;;\n\t\ttap)\n\t\t\tNET_USER=false\n\t\t\tNET_TAP=true\n\t\t\t;;\n\t\tvhost)\n\t\t\tNET_USER=false\n\t\t\tNET_TAP=true\n\t\t\tNET_VHOST=true\n\t\t\t;;\n\t\t*)\n\t\t\techo \"Invalid net '$OPTARG'\"\n\t\t\texit 1\n\t\t\t;;\n\t\tesac\n\t\t;;\n\tesac\ndone\nshift $((OPTIND - 1))\n\necho $TEST_PATH\n\nif [[ ! -z \"$IMAGE\" && -e \"${IMAGE/.img/.fixup}\" ]]; then\n\tIMAGE_FIXUP=\"${IMAGE/.img/.fixup}\"\nfi\n\nif [[ ! -z \"$IMAGE_FIXUP\" ]]; then\n\tsay Using fixup script ${IMAGE_FIXUP}!\n\t. \"$IMAGE_FIXUP\"\nfi\n\nif $GUEST; then\n\tguest\nelse\n\tkernel=\"$1\"\n\tshift\n\n\texport HOSTNAME=\"$HOST\"\n\n\tif $NET_TAP; then\n\t\tif ! ip link show dev qtap0 &>/dev/null; then\n\t\t\techo \"Couldn't find qtap0 tap device, do:\"\n\t\t\techo \"$ sudo ip tuntap add dev qtap0 mode tap multi_queue\"\n\t\t\techo \"$ sudo ip addr add 10.10.10.1/24 dev qtap0\"\n\t\t\techo \"$ sudo ip link set dev qtap0 up\"\n\t\t\techo \"$ sudo ip tuntap add dev qtap1 mode tap\"\n\t\t\techo \"$ sudo ip addr add 10.10.11.1/24 dev qtap1\"\n\t\t\techo \"$ sudo ip link set dev qtap1 up\"\n\t\t\texit 1\n\t\tfi\n\n\t\tif $TAP_MQ; then\n\t\t\tV4_ADDR=10.10.10.2\n\t\t\tV4_PREFIX=24\n\t\telse\n\t\t\tV4_ADDR=10.10.11.2\n\t\t\tV4_PREFIX=24\n\t\tfi\n\tfi\n\n\tif [[ -z \"$kernel\" ]]; then\n\t\tif [[ -e \"arch/x86/boot/bzImage\" ]]; then\n\t\t\tkernel=\"arch/x86/boot/bzImage\"\n\t\telif [[ -e \"arch/arm64/boot/Image\" ]]; then\n\t\t\tkernel=\"arch/arm64/boot/Image\"\n\t\tfi\n\tfi\n\n\tif [[ -z \"$ARCH\" ]]; then\n\t\tif file $kernel | grep -q x86; then\n\t\t\tARCH=x86_64\n\t\telif file $kernel | grep -q ARM64; then\n\t\t\tARCH=arm64\n\t\tfi\n\tfi\n\n\t[ -n \"$ARCH\" ] || usage \"unknown arch\"\n\n\thost \"$kernel\"\nfi\n"
  },
  {
    "path": "scripts/q-script/yifei-q",
    "content": "#!/bin/bash\n# based on: https://github.com/fomichev/dotfiles/blob/master/bin/q\n\nusage() {\n\techo \"q [options] [path to bzImage] [script]\"\n\techo\n\techo \"Run it from the kernel directory (make sure .config is there)\"\n\techo\n\techo \"options:\"\n\techo \"    m - run depmod and modprobe\"\n\techo \"    c - pass extra kernel cmdline options\"\n\techo \"    s - start SSH server\"\n\texit 1\n}\n\n# This function is called _BEFORE_ QEMU starts (on host).\nhost() {\n\tlocal kernel=\"$1\"\n\tshift\n\n\tif [ -z \"$kernel\" ]; then\n\t\tif [ -e \"arch/x86/boot/bzImage\" ]; then\n\t\t\tkernel=\"arch/x86/boot/bzImage\"\n\t\tfi\n\t\t[ -n \"$kernel\" ] || usage\n\tfi\n\t[ -e \".config\" ] || usage\n\n\tlocal cmdline\n\n\tlocal fs\n\tfs+=\" -nodefaults\"\n\tfs+=\" -fsdev local,multidevs=remap,id=vfs1,path=/,security_model=none,readonly=on\"\n\tfs+=\" -fsdev local,multidevs=remap,id=vfs2,path=$(pwd),security_model=none\"\n\tfs+=\" -device virtio-9p-pci,fsdev=vfs1,mount_tag=/dev/root\"\n\tfs+=\" -device virtio-9p-pci,fsdev=vfs2,mount_tag=/dev/kernel\"\n\n\tlocal console\n\tconsole+=\" -display none\"\n\tconsole+=\" -serial mon:stdio\"\n\tconsole+=\" -serial tcp::1235,server,nowait\"\n\n\tcmdline+=\" earlyprintk=serial,ttyS0,115200\"\n\tcmdline+=\" console=ttyS0,115200\"\n\tcmdline+=\" kgdboc=ttyS1,115200\"\n\n\tlocal net\n\tif [ \"$SSH\" = \"y\" ]; then\n    # check container env assume docker\n\t\tnet+=\" -netdev user,id=virtual,hostfwd=tcp:127.0.0.1:52222-:22,hostfwd=tcp::11211-:11211,hostfwd=udp::11211-:11211\"\n\telse\n\t\tnet+=\" -netdev user,id=virtual\"\n\tfi\n\tnet+=\" -device virtio-net-pci,netdev=virtual\"\n\n\tlocal opts\n\t[ \"$MODULES\" = \"y\" ] && opts+=\" -m\"\n\t[ \"$SSH\" = \"y\" ] && opts+=\" -s\"\n\n\tcmdline+=\" rootfstype=9p\"\n\tcmdline+=\" rootflags=version=9p2000.L,trans=virtio,msize=104857600,access=any\"\n\tcmdline+=\" ro\"\n\tcmdline+=\" nokaslr\"\n\tcmdline+=\" $CMDLINE\"\n\tcmdline+=\" init=/bin/sh -- -c \\\"$(realpath $0) -g $opts -H $HOME -k '$(pwd)' -a '$*'\\\"\"\n\n\tqemu-system-x86_64 \\\n\t\t-nodefaults \\\n\t\t-no-reboot \\\n\t\t-machine accel=kvm:tcg \\\n\t\t-device i6300esb \\\n\t\t-device virtio-rng-pci \\\n\t\t-cpu host \\\n\t\t-smp $NRCPU \\\n\t\t-m $MEMORY \\\n\t\t$fs \\\n\t\t$console \\\n\t\t$net \\\n\t\t$QEMUARG \\\n\t\t-kernel \"$kernel\" \\\n\t\t-append \"$cmdline\" -s\n\n\t# qemu-system-x86_64 \\\n\t# \t-nodefaults \\\n\t# \t-d int \\\n\t# \t-machine accel=tcg \\\n\t# \t-watchdog i6300esb \\\n\t# \t-device virtio-rng-pci \\\n\t# \t-cpu max \\\n\t# \t-smp $NRCPU \\\n\t# \t-m $MEMORY \\\n\t# \t$fs \\\n\t# \t$console \\\n\t# \t$net \\\n\t# \t$QEMUARG \\\n\t# \t-kernel \"$kernel\" \\\n\t# \t-append \"$cmdline\" -s\n}\n\nsay() {\n\ttrap 'tput sgr0' 2 #SIGINT\n\ttput setaf 2\n\techo \">\" \"$@\"\n\ttput sgr0\n}\n\n# This function is called _AFTER_ QEMU starts (on guest).\nguest() {\n\texport PATH=/bin:/sbin:/usr/bin:/usr/sbin\n\n\tsay pivot root\n\n\tmount -n -t proc -o nosuid,noexec,nodev proc /proc/\n\n\tmount -n -t tmpfs tmpfs /tmp\n\tmkdir -p /tmp/rootdir-overlay/{lower,upper,work,mnt}\n\tmount --bind / /tmp/rootdir-overlay/lower\n\tmount -t overlay overlay -o lowerdir=/tmp/rootdir-overlay/lower,upperdir=/tmp/rootdir-overlay/upper,workdir=/tmp/rootdir-overlay/work /tmp/rootdir-overlay/mnt\n\tpivot_root /tmp/rootdir-overlay/mnt{,/mnt}\n\tcd /\n\n\tsay early setup\n\n\tmount -n -t sysfs -o nosuid,noexec,nodev sys /sys/\n\n\tmount -n -t tmpfs tmpfs /tmp\n\tmount -n -t tmpfs tmpfs /var/log\n\tmount -n -t tmpfs tmpfs /run\n\n\trm -f /etc/fstab\n\ttouch /etc/fstab\n\n\tmount -n -t proc -o nosuid,noexec,nodev proc /proc/\n\tmount -n -t configfs configfs /sys/kernel/config\n\tmount -n -t debugfs debugfs /sys/kernel/debug\n\tmount -n -t securityfs security /sys/kernel/security\n\tmount -n -t devtmpfs -o mode=0755,nosuid,noexec devtmpfs /dev\n\n\tmkdir -p -m 0755 /dev/shm /dev/pts\n\tmount -n -t devpts -o gid=tty,mode=620,noexec,nosuid devpts /dev/pts\n\tmount -n -t tmpfs -o mode=1777,nosuid,nodev tmpfs /dev/shm\n\n\tln -s /proc/self/fd /dev/fd\n\n\tmount --move /mnt /tmp\n\tmount -n -t tmpfs tmpfs /mnt\n\tmkdir /mnt/base-root\n\tmount --move /tmp /mnt/base-root\n\n\tlocal kver=\"`uname -r`\"\n\tlocal mods=\"$(find /sys/devices -type f -name modalias -print0 | xargs -0 cat | sort | uniq)\"\n\tlocal mods_nr=$(echo \"$mods\" | wc -w)\n\n\tsay modules /lib/modules/$kver $mods_nr modules\n\tmount -n -t 9p -o version=9p2000.L,trans=virtio,msize=104857600 /dev/kernel $KERNEL\n\tmount -n -t tmpfs tmpfs /lib/modules\n\tmkdir \"/lib/modules/$kver\"\n\tln -s $KERNEL \"/lib/modules/$kver/source\"\n\tln -s $KERNEL \"/lib/modules/$kver/build\"\n\tln -s $KERNEL \"/lib/modules/$kver/kernel\"\n\n\tcp $KERNEL/modules.builtin \"/lib/modules/$kver/modules.builtin\"\n\tcp $KERNEL/modules.builtin.modinfo \"/lib/modules/$kver/modules.builtin.modinfo\"\n\tcp $KERNEL/modules.order \"/lib/modules/$kver/modules.order\"\n\n\t# make sure config points to the right place\n\tmount -n -t tmpfs tmpfs /boot\n\tln -s $KERNEL/.config /boot/config-$kver\n\n\tif [ \"$MODULES\" = \"y\" ]; then\n\t\tif [ ! -e $KERNEL/modules.dep.bin ]; then\n\t\t\tsay modules.dep.bin not found, running depmod, may take awhile\n\t\t\tdepmod -a 2>/dev/null\n\t\tfi\n\t\tmodprobe -q -a -- $mods\n\tfi\n\n\tsay networking\n\n\thostname q\n\trm -f /etc/hostname\n\techo q > /etc/hostname\n\n\tip link set dev lo up\n\n\trm -f /etc/resolv.conf\n\techo \"nameserver 8.8.8.8\" > /etc/resolv.conf\n\n\tlocal dev=$(ls -d /sys/bus/virtio/drivers/virtio_net/virtio* |sort -g |head -n1)\n\tlocal iface=$(ls $dev/net)\n\tsay dhcp on iface $iface\n\tip link set dev $iface up\n\tbusybox udhcpc -i $iface -p /run/udhcpc \\\n\t\t-s /usr/share/udhcpc/default.script -q -t 1 -n -f\n\n\tsay setup cgroups\n\tsysctl -q kernel.allow_bpf_attach_netcg=0 &>/dev/null\n\tmount -t cgroup2 none /sys/fs/cgroup\n\n\tsay setup bpf\n\tsysctl -q net.core.bpf_jit_enable=1\n\tsysctl -q net.core.bpf_jit_kallsyms=1\n\tsysctl -q net.core.bpf_jit_harden=0\n\tmount -t bpf bpffs /sys/fs/bpf\n\tulimit -l unlimited &>/dev/null # EINVAL when loading more than 3 bpf programs\n\tulimit -n 819200 &>/dev/null\n\tulimit -a &>/dev/null\n\n\tsay root passwd\n\trm -f /etc/{shadow,gshadow}\n\tpwconv\n\tgrpconv\n\n\tmount --bind / /mnt\n\tusermod -R /mnt -d \"$HOME\" root\n\tumount /mnt\n\n  # For system cannot get ip addr by udhcpc\n  local ip_address=$(ip -4 addr show $iface | grep -oP '(?<=inet\\s)\\d+(\\.\\d+){3}')\n  local default_route=$(ip route | grep default)\n  if [[ -z \"$ip_address\" ]]; then\n      ip a add 10.0.2.15/24 dev eth0 \n  fi\n  if [[ -z \"$default_route\" ]]; then\n    ip route add default via 10.0.2.2\n  fi\n\n\tif [ \"$SSH\" = \"y\" ]; then\n\t\tsay setup sshd: '$ ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@localhost -p 52222'\n\t\tmask-dir () {\n\t\t\ttouch \"$1\"\n\t\t\tsetfattr -n trusted.overlay.opaque -v y /mnt/base-root/tmp/rootdir-overlay/upper/\"$1\"\n\t\t\tmount -o remount /\n\t\t}\n\t\tmask-dir /etc/ssh/\n\n\t\tcat << 'EOF' > /etc/pam.d/sshd\naccount sufficient pam_permit.so\nauth sufficient pam_permit.so\npassword sufficient pam_permit.so\nsession sufficient pam_permit.so\nEOF\n\n\t\tssh-keygen -A\n    mkdir -p /run/sshd\n\t\t`which sshd` -p 22 -o UsePAM=yes -o PermitRootLogin=yes -f /dev/null -E /var/log/sshd\n\tfi\n\n\tsay root environment\n\ncat << EOF >> $HOME/.profile\nexport KERNEL=$KERNEL\n\nexport PATH=\\$HOME/local/bin:\\$PATH\nexport PATH=\\$KERNEL/tools/bpf/bpftool:\\$PATH\nexport PATH=\\$KERNEL/tools/perf:\\$PATH\nexport LD_LIBRARY_PATH=/inner_unikernels/libiu:/inner_unikernels/tools/lib/bpf:$LD_LIBRARY_PATH\nEOF\n\n\tcat << EOF >> $HOME/.bashrc\nmask-dir () {\n\ttouch \"\\$1\"\n\tsetfattr -n trusted.overlay.opaque -v y /mnt/base-root/tmp/rootdir-overlay/upper/\"\\$1\"\n\tmount -o remount /\n}\n\nsource $KERNEL/tools/bpf/bpftool/bash-completion/bpftool\n\neval \\$(resize)\nEOF\n\n\tcd $KERNEL\n\n\tif [ -n \"$ARGS\" ]; then\n\t\tsay non-interactive bash script\n\t\tsetsid bash -l -c \"$ARGS\"\n\t\tif [ ! $? -eq 0 ]; then\n\t\t\tsay script failed, starting interactive console\n\t\t\tsetsid bash -l 0<>\"/dev/ttyS0\" 1>&0 2>&0\n\t\tfi\n\telse\n\t\tsay interactive bash\n\t\tsetsid bash -l 0<>\"/dev/ttyS0\" 1>&0 2>&0\n\tfi\n\n\techo\n\tsay poweroff\n\tpoweroff -f\n\techo o > /proc/sysrq-trigger\n\tsleep 30\n}\n\nGUEST=n\nMODULES=n\nSSH=n\nCMDLINE=\"\"\nQEMUARG=\"\"\n\nNRCPU=4\nMEMORY=8192\n\nwhile getopts \"hgmsk:c:a:H:N:M:q:\" opt; do\n\tcase $opt in\n\t\th) usage ;;\n\t\tg) GUEST=y ;;\n\t\tm) MODULES=y ;;\n\t\ts) SSH=y ;;\n\t\tk) KERNEL=\"$OPTARG\" ;;\n\t\tc) CMDLINE=\"$OPTARG\" ;;\n\t\ta) ARGS=\"$OPTARG\" ;;\n\t\tH) export HOME=$OPTARG ;;\n\t\tM) MEMORY=\"$OPTARG\" ;;\n\t\tN) NRCPU=\"$OPTARG\" ;;\n\t\tq) QEMUARG=\"$OPTARG\" ;;\n\tesac\ndone\nshift $((OPTIND -1))\n\n[ \"$GUEST\" = \"y\" ] && guest \"$@\" || host \"$@\"\n"
  },
  {
    "path": "scripts/sanity_tests/run_tests.py",
    "content": "#!/usr/bin/env bash\n\n''':' ; exec \"$(command -v python)\" \"$0\" \"$@\"\n'''\n\nimport os\nimport subprocess\nimport sys\n\nfrom pathlib import Path\n\nsample_path = os.environ.get(\"SAMPLE_PATH\")\nif not sample_path:\n    print(\"Error: SAMPLE_PATH environment variable is required\")\n    sys.exit(1)\nsample = Path(sample_path)\n\nq_script_env = os.environ.get(\"Q_SCRIPT\")\nif not q_script_env:\n    print(\"Error: Q_SCRIPT environment variable is required\")\n    sys.exit(1)\nq_script = Path(q_script_env)\n\n# Set Path env\nkernel_path_env = os.environ.get(\"KERNEL_PATH\")\nif not kernel_path_env:\n    print(\"Error: KERNEL_PATH environment variable is required\")\n    sys.exit(1)\nkernel_path = Path(kernel_path_env)\n\n\ndef main():\n    os.chdir(kernel_path)\n    test_path = sample.joinpath(\"runtest.py\")\n    cmd = \" \".join([str(q_script), \"-t\", str(test_path)])\n    try:\n        # print(cmd)\n        result = subprocess.run(\n            cmd, timeout=180, shell=True, capture_output=True, text=True\n        )\n        # Debug: save QEMU output for troubleshooting\n        with open(\"qemu_stdout.log\", \"w\") as f:\n            f.write(result.stdout)\n        with open(\"qemu_stderr.log\", \"w\") as f:\n            f.write(result.stderr)\n        print(f\"QEMU exit code: {result.returncode}\", file=sys.stderr)\n        output = subprocess.run(\n            \"cat auto_grade.txt | grep success\",\n            capture_output=True,\n            text=True,\n            shell=True,\n        )\n        if output.stdout.strip() != \"success\":\n            print(\"\", end=\"\\x1b[1K\\r\")\n            print(\"   \\033[91mFailed\\033[0m  %s\" % sample.name)\n            exit(1)\n\n    except Exception:\n        print(f\"{sample.name} test run failed\", file=sys.stderr)\n        subprocess.run(\"pkill qemu-system-x86\", shell=True)\n    finally:\n        subprocess.run(\"rm auto_grade.txt\", shell=True, check=True)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "tools/memcached_benchmark/.cargo/config.toml",
    "content": "[env]\nCC = { value = \"clang\", force = true }\n\n[target.x86_64-unknown-linux-gnu]\nlinker = \"clang\"\nrustflags = [\n\t\"-Zthreads=8\",\n\t\"-Ctarget-cpu=native\",\n\t\"-Clinker-plugin-lto\",\n\t\"-Clink-args=-flto=thin -fuse-ld=mold -Wl,-O1 -Wl,--as-needed -Wl,--gc-sections\",\n]\n"
  },
  {
    "path": "tools/memcached_benchmark/.gitignore",
    "content": "/target\nbmc-results.csv\n# Devenv\n.devenv*\ndevenv.local.nix\n\n# direnv\n.direnv\n\n# pre-commit\n.pre-commit-config.yaml\n"
  },
  {
    "path": "tools/memcached_benchmark/Cargo.toml",
    "content": "[package]\nname = \"memcached_benchmark\"\nversion = \"0.2.0\"\nedition = \"2024\"\nauthors = [\"Ruowen Qin ruowenq2@illinois.edu\"]\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\nmemcache = { version = \"0.19\", default-features = false }\nrand = \"0\"\nrand_distr = \"0\"\nclap = { version = \"4\", features = [\"derive\"] }\nrayon = \"1\"\ntokio = { version = \"1\", features = [\"full\"] }\nzstd = { version = \"0\", features = [\"zstdmt\", \"thin-lto\"] }\nserde = { version = \"1\", features = [\"derive\"] }\nserde_yaml = \"0.9\"\nserde_json = \"1\"\nmemcache-async = \"0.10\"\ntokio-util = { version = \"0.7\", features = [\"rt\", \"compat\"] }\nchacha20 = \"0\"\nlog = \"0\"\nenv_logger = { version = \"0\" }\nmimalloc = \"0\"\nanyhow = \"1\"\n\n\n[dev-dependencies]\nassert_cmd = \"2\"\npredicates = \"3\"\ntempfile = \"3\"\ntest-log = \"0\"\nduct = \"1\"\n\n[profile.release]\nopt-level = 3\ndebug = false\ncodegen-units = 1\npanic = \"abort\"\nstrip = true\n"
  },
  {
    "path": "tools/memcached_benchmark/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2024 Ruowen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "tools/memcached_benchmark/README.md",
    "content": "# memcached_benchmark"
  },
  {
    "path": "tools/memcached_benchmark/bench.py",
    "content": "import csv\nimport resource\nimport subprocess\n\n\nCLIENT_IP = \"192.168.50.253\"\n\nimport numpy as np\nfrom tqdm import tqdm\nfrom pathlib import Path\n\nclass MemcachedCtx:\n    def __init__(self, start, stop):\n        self.start = start\n        self.stop = stop\n\n    def __enter__(self):\n        subprocess.run(self.start, check=True, capture_output=True)\n\n    def __exit__(self, *args):\n        subprocess.run(self.stop, check=True, capture_output=True)\n\ndef increase_fd_limit(new_limit):\n    # Get the current soft and hard limits\n    soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)\n    print(f\"Current Limits - Soft: {soft_limit}, Hard: {hard_limit}\")\n\n    # Check if the new limit is within the permissible range\n    if new_limit <= hard_limit:\n        # Set the new soft limit\n        resource.setrlimit(resource.RLIMIT_NOFILE, (new_limit, hard_limit))\n        soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)\n        print(f\"File descriptor soft_limit increased to { soft_limit }\")\n        print(f\"File descriptor hard_limit increased to { hard_limit }\")\n    else:\n        print(\"Requested limit exceeds the hard limit. Cannot increase beyond the hard limit.\")\n\ndef run_bench():\n    # cmd = 'cargo run -r -- bench -n 200000000 -t 40 -s 10.0.1.1 -p 11211'.split()\n    cmd = 'cargo run -r -- bench -n 100000000 -t 32 -s 10.0.1.1 -p 11211 | tee /tmp/run_bench_temp'\n    subprocess.run(cmd, check=True, capture_output=False, text=True, shell=True)\n    output = Path(\"/tmp/run_bench_temp\").read_text().split(\"\\n\")\n    output = list(filter(lambda x: \"Throughput across all threads\" in x, output))\n    assert len(output) == 1\n    return np.float64(output[0].split(\": \")[1].split()[0])\n\ndef run_vanilla(nr_threads):\n    start = [*f'ssh {CLIENT_IP} -t'.split(),\n             'sudo /root/run-memcached.sh %d' % nr_threads]\n\n    stop = [*f'ssh {CLIENT_IP} -t'.split(),\n            'sudo /root/stop-memcached.sh %d' % nr_threads]\n\n    with MemcachedCtx(start, stop):\n        result = run_bench()\n\n    return result\n\ndef run_bpf(nr_threads):\n    start = [*f'ssh {CLIENT_IP} -t'.split(),\n             'sudo /root/attach-bpf.sh %d' % nr_threads]\n\n    stop = [*f'ssh {CLIENT_IP} -t'.split(),\n            'sudo /root/detach-bpf.sh %d' % nr_threads]\n\n    with MemcachedCtx(start, stop):\n        result = run_bench()\n\n    return result\n\ndef run_rust(nr_threads):\n    start = [*f'ssh {CLIENT_IP} -t'.split(),\n             'sudo /root/attach-rust.sh %d' % nr_threads]\n\n    stop = [*f'ssh {CLIENT_IP} -t'.split(),\n            'sudo /root/detach-rust.sh %d' % nr_threads]\n\n    with MemcachedCtx(start, stop):\n        result = run_bench()\n\n    return result\n\ndef main():\n    max_cpu = 8\n    rounds = 10\n    increase_fd_limit(202400)\n\n    data = {\n        'vanilla': [[0 for j in range(rounds)] for i in range(max_cpu)],\n        'bpf': [[0 for j in range(rounds)] for i in range(max_cpu)],\n        'rust': [[0 for j in range(rounds)] for i in range(max_cpu)],\n    }\n\n    for i in tqdm(range(max_cpu), desc=\" outer loop\", position=0):\n        for j in tqdm(range(rounds), desc=\" inner loop\", position=1, leave=False):\n            data['vanilla'][i][j] = run_vanilla(i + 1)\n            data['bpf'][i][j] = run_bpf(i + 1)\n            data['rust'][i][j] = run_rust(i + 1)\n\n    result = [('nr_cpu', *data.keys(),\n               *list(map(lambda x: x + '-stdev', data.keys())))]\n\n    for i in range(max_cpu):\n        row = [i]\n\n        for v in data.values():\n            row.append(np.mean(v[i]))\n\n        for v in data.values():\n            row.append(np.std(v[i]))\n\n        result.append(tuple(row))\n\n    with open('bmc-results.csv', 'w', newline='') as out_f:\n        writer = csv.writer(out_f)\n        writer.writerows(result)\n\n    return 0\n\nif __name__ == '__main__':\n    exit(main())\n"
  },
  {
    "path": "tools/memcached_benchmark/flake.nix",
    "content": "{\n  description = \"Rust development environment\";\n\n  inputs = {\n    nixpkgs.url = \"github:NixOS/nixpkgs/nixos-unstable\";\n    rust-overlay.url = \"github:oxalica/rust-overlay\";\n    flake-utils.url = \"github:numtide/flake-utils\";\n  };\n\n  outputs = { self, nixpkgs, rust-overlay, flake-utils, ... }:\n    flake-utils.lib.eachDefaultSystem (system:\n      let\n        overlays = [ (import rust-overlay) ];\n        pkgs = import nixpkgs {\n          inherit system overlays;\n        };\n\n        # 1. Replicate languages.rust\n        rustToolchain = pkgs.rust-bin.nightly.latest.default.override {\n          extensions = [\n            \"rust-src\"\n            \"rustc\"\n            \"clippy\"\n            \"rust-analyzer\"\n            \"rustfmt\"\n          ];\n        };\n\n        # Extract LLVM major version from the Rust toolchain via IFD\n        rustcLlvmVersion = pkgs.runCommand \"rustc-llvm-version\" {\n          nativeBuildInputs = [ rustToolchain ];\n        } ''\n          rustc -vV | sed -n 's/LLVM version: \\([0-9]*\\).*/\\1/p' | tr -d '\\n' > $out\n        '';\n        llvmMajor = builtins.readFile rustcLlvmVersion;\n        llvmPackages = pkgs.\"llvmPackages_${llvmMajor}\";\n      in\n      {\n        devShells.default = pkgs.mkShell {\n          buildInputs = [\n            pkgs.git\n            pkgs.mold\n            llvmPackages.clangUseLLVM\n            pkgs.memcached\n            rustToolchain\n          ];\n\n          shellHook = ''\n            # enterShell logic\n            clang --version\n            rustc --version\n          '';\n        };\n      }\n    );\n}\n"
  },
  {
    "path": "tools/memcached_benchmark/rustfmt.toml",
    "content": "max_width = 80\nbinop_separator = \"Back\"\nreorder_impl_items = true\nwrap_comments = true\nimports_granularity = \"Module\"\ngroup_imports = \"StdExternalCrate\"\n"
  },
  {
    "path": "tools/memcached_benchmark/src/cli.rs",
    "content": "use clap::{Parser, Subcommand};\n\nuse crate::Protocol;\n\n#[derive(Parser)]\n#[command(author, version, about, long_about = None)]\npub(crate) struct Cli {\n    #[command(subcommand)]\n    pub(crate) command: Commands,\n}\n\n#[derive(Debug, Subcommand)]\npub(crate) enum Commands {\n    #[command(arg_required_else_help = true)]\n    Bench {\n        /// memcached server addr\n        #[arg(short, long, required = true)]\n        server_address: String,\n\n        #[arg(short, long, default_value = \"11211\")]\n        port: String,\n\n        /// key size to generate random memcached key\n        #[arg(short, long, default_value = \"16\")]\n        key_size: usize,\n\n        /// value size to generate random memcached value\n        #[arg(short, long, default_value = \"32\")]\n        value_size: usize,\n\n        /// verify the value after get command\n        #[arg(long, default_value = \"false\")]\n        validate: bool,\n\n        /// number of test entries to generate\n        #[arg(short, long, default_value = \"100000\")]\n        nums: usize,\n\n        /// number of threads to run\n        #[arg(short, long, default_value = \"4\")]\n        threads: usize,\n\n        /// udp or tcp protocol for memcached\n        #[arg(short = 'l', long, default_value_t = Protocol::Udp , value_enum)]\n        protocol: Protocol,\n\n        /// number of dict entries to generate\n        #[arg(short, long, default_value = \"1000000\")]\n        dict_entries: usize,\n\n        /// load the prepared test_entries from disk\n        #[arg(long, default_value = \"false\")]\n        load_bench_entries: bool,\n\n        /// skip set memcached value if the data is already imported\n        #[arg(long, default_value = \"false\")]\n        skip_set: bool,\n\n        /// bounded mpsc channel for communicating between asynchronous tasks\n        /// with backpressure\n        #[arg(long, default_value = \"200\")]\n        pipeline: usize,\n\n        /// connection pool size for TCP operations\n        #[arg(long, default_value = \"64\")]\n        tcp_pool_size: usize,\n\n        /// connection pool size for UDP operations\n        #[arg(long, default_value = \"128\")]\n        udp_pool_size: usize,\n\n        /// timeout in milliseconds for operations\n        #[arg(long, default_value = \"1000\")]\n        timeout_ms: u64,\n\n        /// dict path to load\n        #[arg(\n            short = 'f',\n            long,\n            default_value = \"test_dict.yml.zst\",\n            conflicts_with = \"key_size\",\n            conflicts_with = \"dict_entries\"\n        )]\n        dict_path: String,\n    },\n    GenTestdict {\n        /// key size to generate random memcached key\n        #[arg(short, long, default_value = \"16\")]\n        key_size: usize,\n\n        /// value size to generate random memcached value\n        #[arg(short, long, default_value = \"32\")]\n        value_size: usize,\n\n        /// number of dict entries to generate\n        #[arg(short, long, default_value = \"1000000\")]\n        dict_entries: usize,\n\n        /// dict path to store\n        #[arg(short = 'f', long, default_value = \"test_dict.yml.zst\")]\n        dict_path: String,\n    },\n}\n"
  },
  {
    "path": "tools/memcached_benchmark/src/dict.rs",
    "content": "use std::collections::HashMap;\nuse std::mem::size_of_val;\nuse std::sync::Arc;\n\nuse chacha20::ChaCha8Rng;\nuse log::{debug, info};\nuse rand::distr::{Alphanumeric, SampleString};\nuse rand::{RngExt, SeedableRng};\nuse rand_distr::Zipf;\nuse rayon::prelude::*;\n\nuse crate::Protocol;\nuse crate::fs::write_hashmap_to_file;\n\nconst SEED: u64 = 12312;\n\n/// Generate random string of specified length\npub(crate) fn generate_random_str(len: usize) -> String {\n    Alphanumeric.sample_string(&mut rand::rng(), len)\n}\n\n/// Generate test dictionary for memcached with random keys and values\npub(crate) fn generate_memcached_test_dict(\n    key_size: usize,\n    value_size: usize,\n    nums: usize,\n) -> HashMap<String, String> {\n    // random generate dict for memcached test\n    (0..nums)\n        .into_par_iter()\n        .map(|_| {\n            (\n                generate_random_str(key_size),\n                generate_random_str(value_size),\n            )\n        })\n        .collect()\n}\n\n/// Generate test dict and write to disk\n/// # Arguments\n/// * `key_size` - key size\n/// * `value_size` - value size\n/// * `nums` - number of entries\n/// * `dict_path` - dict path to store\n/// # Returns\n/// * `Result` - Result<HashMap<String, String>, anyhow::Error>\n/// # Example\n/// ```rust\n/// let test_dict = generate_test_dict_write_to_disk(16, 32, 100000, \"test_dict.yml.zst\");\n/// ```\npub(crate) fn generate_test_dict_write_to_disk(\n    key_size: usize,\n    value_size: usize,\n    nums: usize,\n    dict_path: &str,\n) -> anyhow::Result<HashMap<String, String>> {\n    let test_dict = generate_memcached_test_dict(key_size, value_size, nums);\n    debug!(\"test dict len: {}\", test_dict.len());\n    if let Some((key, value)) = test_dict.iter().next() {\n        debug!(\"test dict key size: {}\", size_of_val(key.as_str()));\n        debug!(\"test dict value size: {}\", size_of_val(value.as_str()));\n    } else {\n        return Err(anyhow::anyhow!(\"test dict is empty\"));\n    }\n    write_hashmap_to_file(&test_dict, dict_path)?;\n    info!(\"write test dict to path {}\", dict_path);\n    Ok(test_dict)\n}\n\n/// Generate test entries with Zipf distribution for benchmarking\npub(crate) fn generate_test_entries(\n    test_dict: Arc<HashMap<Arc<String>, Arc<String>>>,\n    nums: usize,\n) -> Vec<(Arc<String>, Arc<String>, Protocol)> {\n    let mut rng = ChaCha8Rng::seed_from_u64(SEED);\n    let zipf = Zipf::new((test_dict.len() - 1) as f64, 0.99).unwrap();\n\n    let keys: Vec<Arc<String>> = test_dict.keys().cloned().collect();\n    (0..nums)\n        .map(|idx| {\n            let key = &keys[rng.sample(zipf) as usize];\n            let value = test_dict.get(key).unwrap();\n            // every 31 element is tcp. udp:tcp = 30:1\n            let protocol = if idx % 31 == 30 {\n                Protocol::Tcp\n            } else {\n                Protocol::Udp\n            };\n            (key.clone(), value.clone(), protocol)\n        })\n        .collect()\n}\n\n/// Analyze the statistics of test entries\n#[allow(dead_code)]\npub(crate) fn test_entries_statistics(\n    test_entries: Arc<Vec<(&String, &String, Protocol)>>,\n) {\n    let mut udp_count: usize = 0;\n    let mut tcp_count: usize = 0;\n\n    // analyze the key distribution base on the frequency\n    let mut key_frequency = HashMap::new();\n\n    // only get the first element in the tuple\n    test_entries.iter().for_each(|(key, _, proto)| {\n        *key_frequency.entry(key.to_string()).or_insert(0) += 1;\n        if *proto == Protocol::Udp {\n            udp_count += 1;\n        } else {\n            tcp_count += 1;\n        }\n    });\n\n    // sort by frequency\n    let mut key_frequency: Vec<_> = key_frequency.into_iter().collect();\n    key_frequency.sort_by(|a, b| a.1.cmp(&b.1));\n\n    // Display the frequency of each item\n    for (key, count) in &key_frequency {\n        if *count < key_frequency.len() / 1000 {\n            continue;\n        }\n        info!(\"{}: {}\", key, count);\n    }\n\n    info!(\"tcp count: {}, udp count: {}\", tcp_count, udp_count);\n}\n"
  },
  {
    "path": "tools/memcached_benchmark/src/fs.rs",
    "content": "use std::collections::HashMap;\nuse std::fs::File;\nuse std::io::{BufRead, BufReader, Write};\nuse std::path::Path;\n\nuse anyhow::Result;\nuse log::{debug, info};\nuse serde::Serialize;\n\nuse crate::Protocol;\n\n/// Write hashmap to a compressed file using zstd\n/// # Arguments\n/// * `hashmap` - hashmap to write to file\n/// * `file_path` - file path to write\n/// # Returns\n/// * `Result` - Result<(), anyhow::Error>\npub(crate) fn write_hashmap_to_file<T: Serialize>(\n    hashmap: &T,\n    file_path: &str,\n) -> Result<()> {\n    // Serialize the hashmap to a YAML string\n    let serialized =\n        serde_yaml::to_string(hashmap).expect(\"Failed to serialize\");\n\n    // Create or open the file\n    let file = File::create(file_path)?;\n\n    // Create a zstd encoder with compression level 7\n    let mut encoder = zstd::stream::write::Encoder::new(file, 7)?;\n\n    // Write the YAML string to the file\n    encoder.write_all(serialized.as_bytes())?;\n    encoder.finish()?;\n\n    Ok(())\n}\n\n/// Loads benchmark entries from disk from a zstd-compressed YAML file.\n///\n/// Although the entries are typically selected randomly from a test dictionary,\n/// there are cases where a fixed sequence of entries is needed to ensure\n/// consistent performance comparisons, and this function is utilized to\n/// retrieve the stored benchmark entries\npub(crate) fn load_bench_entries_from_disk(\n    path: &Path,\n) -> Vec<(String, String, Protocol)> {\n    let file = std::fs::File::open(path).unwrap();\n    let decoder = zstd::stream::read::Decoder::new(file).unwrap();\n    let reader = std::io::BufReader::new(decoder);\n    let test_entries: Vec<(String, String, Protocol)> =\n        serde_yaml::from_reader(reader).unwrap();\n    test_entries\n}\n\n/// Load test dictionary from disk\n///\n/// This function opens a file located at `test_dict_path`, which is expected to\n/// be a zstd-compressed and valid YAML document key-value pair\n/// (`HashMap<String, String>`).\npub(crate) fn load_test_dict(\n    test_dict_path: &std::path::Path,\n) -> anyhow::Result<HashMap<String, String>> {\n    // load dict from file if dict_path is not empty\n    info!(\"loading dict from path {:?}\", test_dict_path);\n    let file = std::fs::File::open(test_dict_path)?;\n    let decoder = zstd::stream::read::Decoder::new(file)?;\n    let reader = BufReader::new(decoder);\n\n    // Deserialize the string into a HashMap\n    let mut test_dict = HashMap::new();\n\n    reader.lines().for_each(|line| {\n        let line = line.unwrap();\n        // Assuming each line in your file is a valid YAML representing a\n        // key-value pair\n        let deserialized_map: HashMap<String, String> =\n            serde_yaml::from_str(&line).unwrap();\n        test_dict.extend(deserialized_map);\n    });\n\n    debug!(\"test dict len: {}\", test_dict.len());\n    if let Some(key) = test_dict.keys().next() {\n        debug!(\"test dict key size: {}\", key.len());\n    }\n    if let Some(value) = test_dict.values().next() {\n        debug!(\"test dict value size: {}\", value.len());\n    }\n    Ok(test_dict)\n}\n"
  },
  {
    "path": "tools/memcached_benchmark/src/get_values.rs",
    "content": "use std::collections::HashMap;\nuse std::sync::Arc;\nuse std::sync::atomic::*;\n\nuse anyhow::Result;\nuse clap::ValueEnum;\nuse log::{info, trace};\nuse memcache_async::ascii::Protocol as MemcacheProtocol;\nuse serde::{Deserialize, Serialize};\nuse tokio::net::{TcpStream, UdpSocket};\nuse tokio::sync::mpsc;\nuse tokio::time::timeout;\nuse tokio_util::compat::TokioAsyncReadCompatExt;\nuse tokio_util::task::TaskTracker;\n\nuse crate::{BUFFER_SIZE, TIMEOUT_COUNTER};\n\n#[derive(\n    ValueEnum, Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize,\n)]\npub(crate) enum Protocol {\n    Udp,\n    Tcp,\n}\n\nstruct TaskData {\n    seq: u16,\n    addr: Arc<String>,\n    key: Arc<String>,\n    test_dict: Arc<HashMap<Arc<String>, Arc<String>>>,\n    validate: bool,\n    key_size: usize,\n    value_size: usize,\n    counter: usize,\n}\n\nfn wrap_get_command(key: Arc<String>, seq: u16) -> Vec<u8> {\n    let mut bytes: Vec<u8> = vec![0, 0, 0, 1, 0, 0];\n    let mut command = format!(\"get {}\\r\\n\", key).into_bytes();\n    let mut seq_bytes = seq.to_be_bytes().to_vec();\n    seq_bytes.append(&mut bytes);\n    seq_bytes.append(&mut command);\n    trace!(\"bytes: {:?}\", seq_bytes);\n    seq_bytes\n}\n\nasync fn socket_task(\n    sockets_pool: Arc<Vec<UdpSocket>>,\n    mut rx: mpsc::Receiver<TaskData>,\n    tracker: TaskTracker,\n) {\n    let mut cnt = 0u64;\n    while let Some(TaskData {\n        seq,\n        addr,\n        key,\n        test_dict,\n        validate,\n        key_size,\n        value_size,\n        counter,\n    }) = rx.recv().await\n    {\n        let socket_pool_clone = Arc::clone(&sockets_pool);\n        cnt += 1;\n        tracker.spawn(async move {\n            let send_timeout = tokio::time::Duration::from_millis(500);\n\n            // Send\n            let socket: &UdpSocket = &socket_pool_clone[counter & 0x1F];\n            let packet = wrap_get_command(key.clone(), seq);\n            // Add timeout action\n            if (timeout(\n                send_timeout,\n                socket.send_to(&packet[..], addr.as_str()),\n            )\n            .await)\n                .is_err()\n            {\n                TIMEOUT_COUNTER.fetch_add(1, Ordering::Relaxed);\n                return;\n            };\n\n            // Then receive\n            let mut buf = [0; BUFFER_SIZE];\n            let my_duration = tokio::time::Duration::from_millis(500);\n\n            if let Ok(Ok((amt, _))) =\n                timeout(my_duration, socket.recv_from(&mut buf)).await\n            {\n                if !validate {\n                    return;\n                }\n                if let Some(value) = test_dict.get(&*key) {\n                    let received = String::from_utf8_lossy(&buf[..amt])\n                        .split(\"VALUE \")\n                        .nth(1)\n                        .unwrap_or_default()\n                        [6 + key_size + 1..6 + key_size + value_size + 1]\n                        .to_string();\n\n                    if received != *value.to_string() {\n                        info!(\n                            \"response not match key {} buf: {} , value: {}\",\n                            key, received, value\n                        );\n                    }\n                }\n            } else {\n                // Timeout occurred - increment the counter\n                TIMEOUT_COUNTER.fetch_add(1, Ordering::Relaxed);\n            }\n        });\n    }\n\n    info!(\"processed tasks: {}\", cnt);\n}\n\npub(crate) async fn get_command_benchmark(\n    test_dict: Arc<HashMap<Arc<String>, Arc<String>>>,\n    send_commands: Vec<(Arc<String>, u16, Protocol, Arc<String>)>,\n    server_address: String,\n    port: String,\n    validate: bool,\n    key_size: usize,\n    value_size: usize,\n    pipeline: usize,\n) -> Result<()> {\n    // assign client address\n    let addr = Arc::new(format!(\"{}:{}\", server_address, port));\n\n    let mut sockets_pool = vec![];\n    for _ in 0..32 {\n        let socket = UdpSocket::bind(\"0.0.0.0:0\")\n            .await\n            .expect(\"couldn't bind to address\");\n        sockets_pool.push(socket);\n    }\n    let sockets_pool = Arc::new(sockets_pool);\n\n    let tcp_addr = format!(\"{}:{}\", server_address, port);\n    let stream = TcpStream::connect(&tcp_addr)\n        .await\n        .expect(\"TCP memcached connection failed\");\n    let mut client = MemcacheProtocol::new(stream.compat());\n\n    let tracker = TaskTracker::new();\n    let cloned_tracker = tracker.clone();\n\n    let start = std::time::Instant::now();\n\n    // Create the channel\n    let (tx, rx) = mpsc::channel(pipeline);\n\n    tracker.spawn(socket_task(sockets_pool, rx, cloned_tracker));\n\n    let mut counter = 0usize;\n    let mut handles = vec![];\n\n    for (key, seq, proto, value) in send_commands {\n        // if tcp, use set request\n        if proto == Protocol::Tcp {\n            client\n                .set(&*key, value.as_bytes(), 0)\n                .await\n                .expect(\"memcached set command failed\");\n            continue;\n        }\n        counter = counter.wrapping_add(1);\n        let send_result = tx.send(TaskData {\n            seq,\n            addr: addr.clone(),\n            key,\n            test_dict: test_dict.clone(),\n            validate,\n            key_size,\n            value_size,\n            counter,\n        });\n        handles.push(send_result);\n    }\n\n    for handle in handles {\n        handle.await?;\n    }\n\n    // Close the channel\n    drop(tx);\n\n    // Wait for the socket task to finish\n    tracker.close();\n    tracker.wait().await;\n\n    let duration = start.elapsed();\n    info!(\"Time elapsed in get_command_benchmark() is: {:?}\", duration);\n\n    Ok(())\n}\n"
  },
  {
    "path": "tools/memcached_benchmark/src/main.rs",
    "content": "#![allow(clippy::too_many_arguments)]\n\nmod cli;\nmod dict;\nmod fs;\nmod get_values;\nmod set_values;\n\nuse std::collections::HashMap;\nuse std::sync::atomic::*;\nuse std::sync::{Arc, OnceLock};\nuse std::vec;\n\n// Global configuration initialized from CLI args\n#[derive(Debug, Clone, Copy)]\npub struct BenchConfig {\n    pub tcp_pool_size: usize,\n    pub udp_pool_size: usize,\n    pub timeout_ms: u64,\n}\n\npub static CONFIG: OnceLock<BenchConfig> = OnceLock::new();\n\nimpl BenchConfig {\n    pub fn get() -> &'static BenchConfig {\n        CONFIG.get().expect(\"BenchConfig not initialized\")\n    }\n}\n\nuse anyhow::{Result, anyhow};\nuse clap::Parser;\nuse cli::{Cli, Commands};\nuse dict::{generate_test_dict_write_to_disk, generate_test_entries};\nuse env_logger::Target;\nuse fs::{load_bench_entries_from_disk, load_test_dict, write_hashmap_to_file};\nuse get_values::{Protocol, get_command_benchmark};\nuse log::{LevelFilter, info};\nuse memcache::MemcacheError;\nuse mimalloc::MiMalloc;\nuse serde_json::json;\nuse set_values::set_memcached_value;\nuse tokio::runtime::Builder;\n\n#[global_allocator]\nstatic GLOBAL: MiMalloc = MiMalloc;\n\nconst BUFFER_SIZE: usize = 1500;\nconst BENCH_ENTRIES_PATH: &str = \"bench_entries.yml.zst\";\n\nstatic TIMEOUT_COUNTER: AtomicUsize = AtomicUsize::new(0);\n\nfn get_server(\n    addr: &String,\n    port: &String,\n    protocol: &Protocol,\n) -> Result<memcache::Client, MemcacheError> {\n    match protocol {\n        Protocol::Udp => memcache::connect(format!(\n            \"memcache+udp://{}:{}?timeout=10\",\n            addr, port\n        )),\n        Protocol::Tcp => memcache::connect(format!(\n            \"memcache://{}:{}?timeout=10\",\n            addr, port\n        )),\n    }\n}\n\nfn run_bench() -> Result<()> {\n    let args = Cli::parse();\n    let Commands::Bench {\n        server_address,\n        port,\n        key_size,\n        value_size,\n        validate,\n        nums,\n        threads,\n        protocol,\n        dict_path,\n        load_bench_entries,\n        dict_entries,\n        skip_set,\n        pipeline,\n        tcp_pool_size,\n        udp_pool_size,\n        timeout_ms,\n    } = args.command\n    else {\n        return Err(anyhow!(\"invalid command\"));\n    };\n\n    // Initialize global configuration\n    let _ = CONFIG.set(BenchConfig {\n        tcp_pool_size,\n        udp_pool_size,\n        timeout_ms,\n    });\n\n    let server = get_server(&server_address, &port, &protocol)?;\n\n    let test_dict_path = std::path::Path::new(dict_path.as_str());\n    let test_dict: HashMap<String, String> = if !test_dict_path.exists() {\n        // if dict_path is empty, generate dict\n        generate_test_dict_write_to_disk(\n            key_size,\n            value_size,\n            dict_entries,\n            dict_path.as_str(),\n        )?\n    } else {\n        load_test_dict(test_dict_path)?\n    };\n    let test_dict: Arc<HashMap<Arc<String>, Arc<String>>> = Arc::new(\n        test_dict\n            .into_iter()\n            .map(|(k, v)| (Arc::new(k), Arc::new(v)))\n            .collect(),\n    );\n\n    // if memcached server is already imported, skip set memcached value\n    if !skip_set {\n        let rt = Builder::new_multi_thread()\n            .enable_all()\n            .thread_name(\"memcached-set\")\n            .event_interval(31)\n            .build()?;\n\n        let test_dict = test_dict.clone();\n        let server_address = server_address.clone();\n        let port = port.clone();\n        rt.block_on(async move {\n            set_memcached_value(test_dict, server_address, port)\n                .await\n                .unwrap()\n        });\n    }\n\n    let test_dict_path = std::path::Path::new(BENCH_ENTRIES_PATH);\n    let test_entries_tmp = if load_bench_entries && test_dict_path.exists() {\n        load_bench_entries_from_disk(test_dict_path)\n    } else {\n        vec![]\n    };\n\n    info!(\"Start to generate get commands for each thread\");\n    let benchmark_entries = if test_entries_tmp.is_empty() {\n        let test_entries = generate_test_entries(test_dict.clone(), nums);\n        if load_bench_entries {\n            let test_entries_write: Vec<(String, String, Protocol)> =\n                test_entries\n                    .clone()\n                    .into_iter() // Iterate over the original vector\n                    .map(|(a, b, c)| {\n                        (\n                            Arc::try_unwrap(a).unwrap_or_else(|a| (*a).clone()),\n                            Arc::try_unwrap(b).unwrap_or_else(|b| (*b).clone()),\n                            c,\n                        )\n                    })\n                    .collect();\n\n            write_hashmap_to_file(&test_entries_write, BENCH_ENTRIES_PATH)?;\n        }\n        test_entries\n    } else {\n        // convert to Vec<(Arc<String>, Arc<String>, Protocol)>\n        test_entries_tmp\n            .iter()\n            .map(|(key, value, proto)| {\n                (Arc::new(key.clone()), Arc::new(value.clone()), *proto)\n            })\n            .collect()\n    };\n    let benchmark_entries = Arc::new(benchmark_entries);\n\n    // analyze test entries statistics\n    // _test_entries_statistics(test_entries.clone());\n\n    let mut send_commands_vec = Vec::new();\n\n    for thread_num in 0..threads {\n        let mut seq: u16 = 0;\n        let mut send_commands = vec![];\n\n        for index in 0..nums / threads {\n            let (key, value, proto) =\n                &benchmark_entries[thread_num * nums / threads + index];\n            // let packet = wrap_get_command(key.clone(), seq);\n            seq = seq.wrapping_add(1);\n            send_commands.push((key.clone(), seq, *proto, value.clone()));\n        }\n\n        send_commands_vec.push(send_commands);\n    }\n\n    let start_time = std::time::SystemTime::now();\n\n    // let rt = Builder::new_multi_thread().enable_all().build()?;\n    let mut handles = vec![];\n    info!(\"Start benchmark\");\n\n    for tid in 0..threads {\n        let test_dict = test_dict.clone();\n        let server_address = server_address.clone();\n        let port = port.clone();\n        let send_commands = send_commands_vec.pop().unwrap();\n        let handle = std::thread::Builder::new()\n            .name(format!(\"bmc-worker-{tid}\"))\n            .spawn(move || {\n                let rt =\n                    Builder::new_current_thread().enable_all().build().unwrap();\n                rt.block_on(async move {\n                    get_command_benchmark(\n                        test_dict,\n                        send_commands,\n                        server_address,\n                        port,\n                        validate,\n                        key_size,\n                        value_size,\n                        pipeline,\n                    )\n                    .await\n                    .unwrap();\n                    info!(\"Finish gen_command_bench {}\", tid);\n                })\n            })\n            .unwrap();\n        handles.push(handle);\n    }\n\n    for handle in handles {\n        handle.join().unwrap();\n    }\n\n    // wait for all tasks to complete\n    info!(\"wait for all tasks to complete\");\n\n    let elapsed_time = start_time.elapsed()?.as_secs_f64();\n    info!(\"Timeout counter {}\", TIMEOUT_COUNTER.load(Ordering::SeqCst));\n    let throughput =\n        (nums - TIMEOUT_COUNTER.load(Ordering::SeqCst)) as f64 / elapsed_time;\n    info!(\n        \"Throughput across all threads: {:.2} reqs/sec, elapsed_time {}\",\n        throughput, elapsed_time\n    );\n\n    macro_rules! build_stats_map {\n    ($result:expr, $($key:expr),*) => {{\n        let mut map = ::std::collections::HashMap::new();\n        $(\n            map.insert($key, &$result[$key]);\n        )*\n        map\n    }};\n}\n\n    // stats\n    let stats = server.stats()?;\n    let result = &stats[0].1;\n    let output = build_stats_map!(\n        result,\n        \"cmd_get\",\n        \"cmd_set\",\n        \"get_hits\",\n        \"get_misses\",\n        \"bytes_read\",\n        \"bytes_written\",\n        \"curr_items\",\n        \"total_items\"\n    );\n    let obj = json!(output);\n    info!(\"{}\", serde_json::to_string_pretty(&obj).unwrap());\n    Ok(())\n}\n\nfn main() -> Result<()> {\n    let args = Cli::parse();\n\n    env_logger::Builder::new()\n        .target(Target::Stdout)\n        .filter_level(LevelFilter::Info)\n        .init();\n\n    match args.command {\n        Commands::Bench { .. } => {\n            run_bench()?;\n        }\n        Commands::GenTestdict {\n            key_size,\n            value_size,\n            dict_entries,\n            dict_path,\n        } => {\n            let _ = generate_test_dict_write_to_disk(\n                key_size,\n                value_size,\n                dict_entries,\n                dict_path.as_str(),\n            )?;\n        }\n    }\n\n    Ok(())\n}\n"
  },
  {
    "path": "tools/memcached_benchmark/src/set_values.rs",
    "content": "use std::collections::HashMap;\nuse std::sync::Arc;\n\nuse anyhow::Result;\nuse log::info;\nuse memcache_async::ascii::Protocol;\nuse tokio::net::TcpStream;\nuse tokio::sync::Semaphore;\nuse tokio::task::JoinSet;\nuse tokio_util::compat::TokioAsyncReadCompatExt;\n\npub(super) async fn set_memcached_value(\n    test_dict: Arc<HashMap<Arc<String>, Arc<String>>>,\n    server_address: String,\n    port: String,\n) -> Result<()> {\n    info!(\"Start set memcached value\");\n    let addr = format!(\"{}:{}\", server_address, port);\n    let mut sockets_pool = vec![];\n    let concurrency_limit = 64;\n\n    for _ in 0..concurrency_limit {\n        let stream = TcpStream::connect(&addr)\n            .await\n            .expect(\"TCP memcached connection failed\");\n        let client = Protocol::new(stream.compat());\n        sockets_pool.push(tokio::sync::Mutex::new(client));\n    }\n    let sockets_pool = Arc::new(sockets_pool);\n\n    let mut set = JoinSet::new();\n    let sem = Arc::new(Semaphore::new(concurrency_limit));\n\n    for (count, (key, value)) in test_dict.iter().enumerate() {\n        let sockets_pool_clone = sockets_pool.clone();\n        let key_clone = key.clone();\n        let value_clone = value.clone();\n        let sem = sem.clone();\n        set.spawn(async move {\n            let _permit = sem.acquire_owned().await;\n            let mut socket = sockets_pool_clone[count & 0x3F].lock().await;\n            socket\n                .set(&*key_clone, value_clone.as_bytes(), 0)\n                .await\n                .expect(\"memcached set command failed\");\n\n            let get_value = socket\n                .get(&*key_clone)\n                .await\n                .expect(\"memcached get command failed\");\n\n            assert_eq!(get_value, value_clone.as_bytes());\n        });\n    }\n\n    while set.join_next().await.is_some() {}\n\n    info!(\"Done set memcached value\");\n\n    Ok(())\n}\n"
  },
  {
    "path": "tools/memcached_benchmark/tests/benchmark_test.rs",
    "content": "use std::thread;\nuse std::time::Duration;\n\nuse anyhow::{Ok, Result};\nuse assert_cmd::assert::OutputAssertExt;\nuse assert_cmd::cargo::cargo_bin_cmd;\nuse duct::{Handle, cmd};\nuse log::{debug, info};\nuse tempfile::TempDir;\nuse test_log::test;\n\nstruct ProcessGuard {\n    handle: Handle,\n}\n\nimpl Drop for ProcessGuard {\n    fn drop(&mut self) {\n        let _ = self.handle.kill();\n        info!(\"Killed memcached process\");\n    }\n}\n\n#[test]\nfn test_memcached_benchmark() -> Result<()> {\n    let memcached_port = \"11211\";\n\n    let memcached_handle =\n        cmd!(\"memcached\", \"-U\", memcached_port, \"-v\").start()?;\n\n    // Wrap in our guard for automatic cleanup\n    let _process_guard = ProcessGuard {\n        handle: memcached_handle,\n    };\n\n    info!(\"Started memcached server on port {}\", memcached_port);\n    thread::sleep(Duration::from_secs(2));\n\n    let temp_dir = TempDir::new()?;\n    let dict_path = temp_dir.path().join(\"test_dict.yml.zst\");\n    debug!(\"temp dir path {}\", dict_path.display());\n\n    let bin_path =\n        std::env::current_exe().expect(\"Failed to get current exe path\");\n    debug!(\"binpath {:?}\", bin_path);\n\n    let gen_dict = cargo_bin_cmd!(env!(\"CARGO_PKG_NAME\"))\n        .args([\n            \"gen-testdict\",\n            \"--key-size\",\n            \"16\",\n            \"--value-size\",\n            \"32\",\n            \"--dict-entries\",\n            \"10000\",\n        ])\n        .unwrap();\n\n    gen_dict.assert().success();\n    info!(\"Generated test dictionary at: {}\", dict_path.display());\n\n    let output = cargo_bin_cmd!(env!(\"CARGO_PKG_NAME\"))\n        .args([\n            \"bench\",\n            \"--server-address\",\n            \"localhost\",\n            \"--port\",\n            memcached_port,\n            \"--key-size\",\n            \"16\",\n            \"--value-size\",\n            \"32\",\n            \"--nums\",\n            \"50000\",\n            \"--threads\",\n            \"2\",\n            \"--protocol\",\n            \"udp\",\n            \"--dict-entries\",\n            \"10000\",\n            \"--pipeline\",\n            \"100\",\n        ])\n        .output()?;\n\n    output.clone().assert().success();\n    let stdout = String::from_utf8(output.stdout)?;\n    let stderr = String::from_utf8(output.stderr)?;\n\n    debug!(\"Benchmark stdout: {}\", stdout);\n    debug!(\"Benchmark stderr: {}\", stderr);\n\n    assert!(stdout.contains(\"Start set memcached value\"));\n    assert!(stdout.contains(\"Throughput across all threads:\"));\n    assert!(stdout.contains(\"Done set memcached value\"));\n\n    Ok(())\n}\n"
  }
]