├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── dependabot.yml ├── pull_request_template.md └── workflows │ ├── ci.yml │ └── publish.yml ├── .gitignore ├── .mergify.yml ├── COPYING ├── Makefile.am ├── README.md ├── bootstrap.sh ├── bors.toml ├── completions └── zsh │ └── _patchelf ├── configure.ac ├── default.nix ├── flake.lock ├── flake.nix ├── m4 └── ax_cxx_compile_stdcxx.m4 ├── patchelf.1 ├── patchelf.nix ├── patchelf.spec.in ├── src ├── Makefile.am ├── elf.h ├── patchelf.cc └── patchelf.h ├── tests ├── Makefile.am ├── add-debug-tag.sh ├── add-rpath.sh ├── args-from-file.sh ├── bar.c ├── basic-flags.sh ├── big-dynstr.sh ├── build-id.sh ├── change-abi.sh ├── contiguous-note-sections.ld ├── contiguous-note-sections.s ├── contiguous-note-sections.sh ├── empty-note ├── empty-note.sh ├── endianness.sh ├── endianness │ ├── Makefile │ ├── ppc64 │ │ ├── libtest.so │ │ └── main │ └── ppc64le │ │ ├── libtest.so │ │ └── main ├── foo.c ├── force-rpath.sh ├── grow-file.sh ├── invalid-elf.sh ├── invalid-elf │ ├── invalid-phdr-offset │ ├── invalid-shdr-name │ ├── invalid-shrstrtab-idx │ ├── invalid-shrstrtab-nonterm │ ├── invalid-shrstrtab-size │ └── invalid-shrstrtab-zero ├── main.c ├── modify-execstack.sh ├── no-dynamic-section.sh ├── no-gnu-hash.sh ├── no-rpath-pie-powerpc.sh ├── no-rpath-prebuild.sh ├── no-rpath-prebuild │ ├── no-rpath-alpha │ ├── no-rpath-amd64 │ ├── no-rpath-armel │ ├── no-rpath-armhf │ ├── no-rpath-hurd-i386 │ ├── no-rpath-i386 │ ├── no-rpath-ia64 │ ├── no-rpath-kfreebsd-amd64 │ ├── no-rpath-kfreebsd-i386 │ ├── no-rpath-mips │ ├── no-rpath-mipsel │ ├── no-rpath-pie-powerpc │ ├── no-rpath-powerpc │ ├── no-rpath-s390 │ ├── no-rpath-sh4 │ └── no-rpath-sparc ├── no-rpath.c ├── no-rpath.sh ├── output-flag.sh ├── overlapping-segments-after-rounding ├── overlapping-segments-after-rounding.sh ├── phdr-corruption.ld ├── phdr-corruption.sh ├── plain-fail.sh ├── plain-needed.sh ├── plain-run.sh ├── print-execstack.sh ├── rename-dynamic-symbols.sh ├── repeated-updates.sh ├── replace-add-needed.sh ├── replace-needed.sh ├── set-empty-rpath.sh ├── set-interpreter-long.sh ├── set-interpreter-same.sh ├── set-interpreter-short.sh ├── set-rpath-library.sh ├── set-rpath-rel-map.sh ├── set-rpath.sh ├── shared-rpath.c ├── shared-rpath.sh ├── short-first-segment.gz ├── short-first-segment.sh ├── shrink-rpath-with-allowed-prefixes.sh ├── shrink-rpath.sh ├── simple.c ├── soname.sh ├── too-many-strtab.c ├── too-many-strtab.sh ├── too-many-strtab2.s └── void.c └── version /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | 12 | A clear and concise description of what the bug is. 13 | 14 | **Steps To Reproduce** 15 | 16 | Please include exact steps with an attached binary so that 17 | another person can reproduce the problem. 18 | 19 | **Expected behavior** 20 | 21 | A clear and concise description of what you expected to happen. 22 | 23 | **`patchelf --version` output** 24 | 25 | **Additional context** 26 | 27 | Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: improvement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | Thank you! 2 | 3 | Please do your best to include [a regression test](https://github.com/NixOS/patchelf/blob/master/tests/build-id.sh) 4 | so that the quality of future releases can be preserved. 5 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: "CI" 2 | on: 3 | pull_request: 4 | push: 5 | jobs: 6 | shellcheck: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | - run: shellcheck tests/*.sh 11 | nix: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: cachix/install-nix-action@v30 16 | - run: nix-build -A hydraJobs.release 17 | ubuntu: 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@v4 21 | - name: get toolchain version 22 | run: | 23 | c++ --version 24 | ld --version 25 | autoconf --version 26 | - run: | 27 | ./bootstrap.sh 28 | mkdir build && cd build 29 | ../configure --with-asan --with-ubsan 30 | make -j$(nproc) check 31 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - '*' 7 | tags: 8 | - '*' 9 | 10 | jobs: 11 | build_tarballs: 12 | name: Build tarballs 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v4 17 | - uses: cachix/install-nix-action@v30 18 | - name: Build tarballs 19 | run: | 20 | nix build -L .#hydraJobs.tarball 21 | install -D ./result/tarballs/*.tar.bz2 ./dist/patchelf-$(cat version).tar.bz2 22 | install -D ./result/tarballs/*.tar.gz ./dist/patchelf-$(cat version).tar.gz 23 | - uses: actions/upload-artifact@v4 24 | with: 25 | name: patchelf-tarball 26 | path: dist/* 27 | 28 | build_windows: 29 | name: Build windows executable 30 | runs-on: ubuntu-latest 31 | steps: 32 | - name: Checkout 33 | uses: actions/checkout@v4 34 | - uses: cachix/install-nix-action@v30 35 | - name: Build windows executable 36 | run: | 37 | nix build -L .#patchelf-win32 .#patchelf-win64 38 | install -D ./result/bin/patchelf.exe ./dist/patchelf-win32-$(cat version).exe 39 | install -D ./result-1/bin/patchelf.exe ./dist/patchelf-win64-$(cat version).exe 40 | - uses: actions/upload-artifact@v4 41 | with: 42 | name: patchelf-windows 43 | path: dist/* 44 | 45 | test_windows: 46 | name: Test windows binaries 47 | needs: [build_windows] 48 | runs-on: windows-latest 49 | steps: 50 | - uses: actions/checkout@v4 51 | - uses: actions/download-artifact@v4 52 | with: 53 | name: patchelf-windows 54 | path: dist 55 | - name: Show binaries 56 | run: dir .\\dist 57 | - name: Test windows 64-bit binary 58 | run: .\\dist\\patchelf-win32-*.exe --version 59 | 60 | - name: Test windows 32-bit binary 61 | run: .\\dist\\patchelf-win64-*.exe --version 62 | 63 | build_musl: 64 | name: Build static musl binaries 65 | needs: [build_tarballs] 66 | runs-on: ubuntu-latest 67 | strategy: 68 | fail-fast: false 69 | matrix: 70 | platform: ["amd64", "i386", "ppc64le", "arm64v8", "arm32v7", "s390x", "riscv64"] 71 | steps: 72 | - name: Set up QEMU 73 | if: matrix.platform != 'amd64' 74 | uses: docker/setup-qemu-action@v3 75 | 76 | - name: Set docker arch 77 | run: | 78 | platform=${{ matrix.platform }} 79 | if [[ $platform == arm64v8 ]]; then 80 | platform=arm64 81 | elif [[ $platform == arm32v7 ]]; then 82 | platform=arm 83 | fi 84 | echo "DOCKER_PLATFORM=$platform" >> $GITHUB_ENV 85 | 86 | - uses: actions/download-artifact@v4 87 | with: 88 | name: patchelf-tarball 89 | path: dist 90 | - name: Build binaries 91 | env: 92 | CXXFLAGS: "-D_FORTIFY_SOURCE=2 -fstack-protector-strong -Wformat -Werror=format-security -O2 -static" 93 | run: | 94 | cat <<EOF > build.sh 95 | set -e 96 | set -x 97 | apk add build-base 98 | tar -xf dist/*.tar.bz2 99 | rm -f dist/* 100 | cd patchelf-* 101 | ./configure --prefix /patchelf 102 | make check || (cat tests/test-suite.log; exit 1) 103 | make install-strip 104 | cd - 105 | tar -czf ./dist/patchelf-\$(cat patchelf-*/version)-\$(uname -m).tar.gz -C /patchelf . 106 | EOF 107 | 108 | if [ "${{ matrix.platform }}" == "i386" ]; then 109 | ENTRYPOINT=linux32 110 | else 111 | ENTRYPOINT= 112 | fi 113 | docker run --platform "$DOCKER_PLATFORM" -e CXXFLAGS -v $(pwd):/gha ${{ matrix.platform }}/alpine:edge ${ENTRYPOINT} sh -ec "cd /gha && sh ./build.sh" 114 | - name: Check binaries 115 | run: | 116 | cat <<EOF > check.sh 117 | set -e 118 | set -x 119 | tar -xf ./dist/patchelf-*-*.tar.gz 120 | ./bin/patchelf --version 121 | EOF 122 | docker run --platform "$DOCKER_PLATFORM" -v $(pwd):/gha ${{ matrix.platform }}/debian:unstable-slim sh -ec "cd /gha && sh ./check.sh" 123 | - uses: actions/upload-artifact@v4 124 | with: 125 | name: patchelf-${{ matrix.platform }} 126 | path: dist/* 127 | 128 | publish: 129 | name: Publish tarballs & binaries 130 | needs: [build_tarballs, build_windows, build_musl] 131 | if: github.event_name == 'push' && github.repository == 'NixOS/patchelf' && startsWith(github.ref, 'refs/tags/') 132 | runs-on: ubuntu-latest 133 | steps: 134 | - uses: actions/download-artifact@v4 135 | with: 136 | pattern: patchelf-* 137 | merge-multiple: true 138 | path: dist 139 | - name: Upload binaries to release 140 | uses: svenstaro/upload-release-action@v2 141 | with: 142 | repo_token: ${{ secrets.GITHUB_TOKEN }} 143 | file: dist/* 144 | tag: ${{ github.ref }} 145 | overwrite: true 146 | file_glob: true 147 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /autom4te.cache/ 2 | 3 | /aclocal.m4 4 | /configure 5 | /config.log 6 | /config.status 7 | /depcomp 8 | /install-sh 9 | /missing 10 | /build-aux/ 11 | 12 | /patchelf.spec 13 | /src/patchelf 14 | 15 | Makefile.in 16 | Makefile 17 | 18 | .deps 19 | *.o 20 | 21 | /tests/*.log 22 | /tests/*.trs 23 | /tests/no-rpath 24 | /tests/no-rpath-*.sh 25 | /tests/*.so 26 | /tests/scratch 27 | /tests/main 28 | /tests/simple 29 | /tests/too-many-strtab 30 | /tests/big-dynstr* 31 | /tests/main-scoped 32 | /tests/libbig-dynstr.debug 33 | /tests/contiguous-note-sections 34 | /tests/simple-pie 35 | /tests/simple-execstack 36 | 37 | .direnv/ 38 | .vscode/ 39 | .idea/ 40 | result 41 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | queue_rules: 2 | - name: default 3 | merge_conditions: 4 | - check-success=Build static musl binaries (amd64) 5 | - check-success=Build static musl binaries (arm32v7) 6 | - check-success=Build static musl binaries (arm64v8) 7 | - check-success=Build static musl binaries (i386) 8 | - check-success=Build static musl binaries (ppc64le) 9 | - check-success=Build static musl binaries (riscv64) 10 | - check-success=Build static musl binaries (s390x) 11 | - check-success=Build tarballs 12 | - check-success=Build windows executable 13 | - check-success=Publish tarballs & binaries 14 | - check-success=Test windows binaries 15 | - check-success=nix 16 | - check-success=shellcheck 17 | - check-success=ubuntu 18 | merge_method: rebase 19 | batch_size: 5 20 | pull_request_rules: 21 | - name: merge using the merge queue 22 | conditions: 23 | - base=master 24 | - label~=merge-queue|dependencies 25 | actions: 26 | queue: {} 27 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | <one line to give the program's name and a brief idea of what it does.> 635 | Copyright (C) <year> <name of author> 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see <https://www.gnu.org/licenses/>. 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | <program> Copyright (C) <year> <name of author> 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | <https://www.gnu.org/licenses/>. 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | <https://www.gnu.org/philosophy/why-not-lgpl.html>. 675 | -------------------------------------------------------------------------------- /Makefile.am: -------------------------------------------------------------------------------- 1 | SUBDIRS = src tests 2 | 3 | EXTRA_DIST = COPYING README.md patchelf.spec version $(man1_MANS) 4 | 5 | man1_MANS = patchelf.1 6 | 7 | doc_DATA = README.md 8 | 9 | zshcompletiondir = $(datadir)/zsh/site-functions 10 | dist_zshcompletion_DATA = completions/zsh/_patchelf 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PatchELF is a simple utility for modifying existing ELF executables and 2 | libraries. In particular, it can do the following: 3 | 4 | * Change the dynamic loader ("ELF interpreter") of executables: 5 | 6 | ```console 7 | $ patchelf --set-interpreter /lib/my-ld-linux.so.2 my-program 8 | ``` 9 | 10 | * Change the `RPATH` of executables and libraries: 11 | 12 | ```console 13 | $ patchelf --set-rpath /opt/my-libs/lib:/other-libs my-program 14 | ``` 15 | 16 | * Shrink the `RPATH` of executables and libraries: 17 | 18 | ```console 19 | $ patchelf --shrink-rpath my-program 20 | ``` 21 | 22 | This removes from the `RPATH` all directories that do not contain a 23 | library referenced by `DT_NEEDED` fields of the executable or library. 24 | For instance, if an executable references one library `libfoo.so`, has 25 | an RPATH `/lib:/usr/lib:/foo/lib`, and `libfoo.so` can only be found 26 | in `/foo/lib`, then the new `RPATH` will be `/foo/lib`. 27 | 28 | In addition, the `--allowed-rpath-prefixes` option can be used for 29 | further rpath tuning. For instance, if an executable has an `RPATH` 30 | `/tmp/build-foo/.libs:/foo/lib`, it is probably desirable to keep 31 | the `/foo/lib` reference instead of the `/tmp` entry. To accomplish 32 | that, use: 33 | 34 | ```console 35 | $ patchelf --shrink-rpath --allowed-rpath-prefixes /usr/lib:/foo/lib my-program 36 | ``` 37 | 38 | * Remove declared dependencies on dynamic libraries (`DT_NEEDED` 39 | entries): 40 | 41 | ```console 42 | $ patchelf --remove-needed libfoo.so.1 my-program 43 | ``` 44 | 45 | This option can be given multiple times. 46 | 47 | * Add a declared dependency on a dynamic library (`DT_NEEDED`): 48 | 49 | ```console 50 | $ patchelf --add-needed libfoo.so.1 my-program 51 | ``` 52 | 53 | This option can be give multiple times. 54 | 55 | * Replace a declared dependency on a dynamic library with another one 56 | (`DT_NEEDED`): 57 | 58 | ```console 59 | $ patchelf --replace-needed liboriginal.so.1 libreplacement.so.1 my-program 60 | ``` 61 | 62 | This option can be give multiple times. 63 | 64 | * Change `SONAME` of a dynamic library: 65 | 66 | ```console 67 | $ patchelf --set-soname libnewname.so.3.4.5 path/to/libmylibrary.so.1.2.3 68 | ``` 69 | 70 | 71 | ## Compiling and Testing 72 | 73 | ### Via Autotools 74 | ```console 75 | ./bootstrap.sh 76 | ./configure 77 | make 78 | make check 79 | sudo make install 80 | ``` 81 | ### Via Nix 82 | 83 | You can build with Nix in several ways. 84 | 85 | 1. Building via `nix build` will produce the result in `./result/bin/patchelf`. If you would like to build _patchelf_ with _musl_ try `nix build .#patchelf-musl` 86 | 87 | 2. You can launch a development environment with `nix develop` and follow the autotools steps above. If you would like to develop with _musl_ try `nix develop .#musl` 88 | 89 | ## Author 90 | 91 | Copyright 2004-2019 Eelco Dolstra <edolstra@gmail.com>. 92 | 93 | ## License 94 | 95 | This program is free software: you can redistribute it and/or modify 96 | it under the terms of the GNU General Public License as published by 97 | the Free Software Foundation, either version 3 of the License, or (at 98 | your option) any later version. 99 | 100 | This program is distributed in the hope that it will be useful, but 101 | WITHOUT ANY WARRANTY; without even the implied warranty of 102 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 103 | General Public License for more details. 104 | 105 | You should have received a copy of the GNU General Public License 106 | along with this program. If not, see <http://www.gnu.org/licenses/>. 107 | -------------------------------------------------------------------------------- /bootstrap.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | autoreconf --verbose --install --force --warnings=all 3 | -------------------------------------------------------------------------------- /bors.toml: -------------------------------------------------------------------------------- 1 | cut_body_after = "" # don't include text from the PR body in the merge commit message 2 | status = [ 3 | "Build windows executable", 4 | "Build tarballs", 5 | "Build static musl binaries (amd64)", 6 | "Build static musl binaries (i386)", 7 | "Build static musl binaries (ppc64le)", 8 | "Build static musl binaries (arm64v8)", 9 | "Build static musl binaries (arm32v7)", 10 | "Build static musl binaries (s390x)", 11 | "Build static musl binaries (riscv64)", 12 | "Test windows binaries", 13 | # this one is only run during release 14 | #"Publish tarballs & binaries", 15 | "nix", 16 | "ubuntu" 17 | ] 18 | -------------------------------------------------------------------------------- /completions/zsh/_patchelf: -------------------------------------------------------------------------------- 1 | #compdef patchelf 2 | 3 | _get_dep() { 4 | # preparm have fewer checks, as they can't be the so to replace 5 | if [[ -f $words[2] ]] { # check if arg #1 is a elf file and not a so 6 | local deps=($(patchelf --print-needed $words[2] 2>/dev/null)) # discard error 7 | if [[ $? -ne 0 ]] || [[ $#deps -eq 0 ]] { # if no dependency or not a elf 8 | _files # fallback to _files 9 | } else { 10 | _values "LIBS" $deps # else use dependencies of the file as candidates 11 | } 12 | # postparm need to check 13 | } elif [[ -f $words[-1] ]] && [[ -z ${words[-1]:e} ]] { # check arg #-1, as most people do like this 14 | local deps=($(patchelf --print-needed $words[-1] 2>/dev/null)) 15 | if [[ $? -ne 0 ]] || [[ $#deps -eq 0 ]] { 16 | _files 17 | } else { 18 | _values "LIBS" $deps 19 | } 20 | } else { 21 | _files 22 | } 23 | } 24 | 25 | local options=( 26 | '--page-size[Uses the given page size]:SIZE:' 27 | '--set-interpreter[Change the dynamic loader of executable]:INTERPRETER:_files' 28 | '(- : *)--print-interpreter[Prints the ELF interpreter of the executable]' 29 | '(- : *)--print-os-abi[Prints the OS ABI of the executable]' 30 | '--set-os-abi[Changes the OS ABI of the executable]:ABI:(none sysv hpux netbsd gnu linux solaris aix irix freebsd tru64 modesto openbsd arm_aeabi arm standalone)' 31 | '(- : *)--print-soname[Prints DT_SONAME entry of .dynamic section]' 32 | '--set-soname[Sets DT_SONAME entry of a library to SONAME]:SONAME:' 33 | '--set-rpath[Change the DT_RUNPATH of the executable or library to RUNPATH]:RUNPATH:_dirs' 34 | '--add-rpath[Add RUNPATH to the existing DT_RUNPATH of the executable or library.]:RUNPATH:_dirs' 35 | '--remove-rpath[Removes the DT_RPATH or DT_RUNPATH entry of the executable or library]' 36 | '--shrink-rpath[Remove from the DT_RUNPATH or DT_RPATH all directories that do not contain a library referenced by DT_NEEDED fields of the executable or library]' 37 | '--allowed-rpath-prefixes[Combined with the "--shrink-rpath" option, this can be used for further rpath tuning]:PREFIXES:' 38 | '(- : *)--print-rpath[Prints the DT_RUNPATH or DT_RPATH for an executable or library]' 39 | '--force-rpath[Forces the use of the obsolete DT_RPATH in the file instead of DT_RUNPATH]' 40 | '--add-needed[Adds a declared dependency on a dynamic library]:LIBRARY:_files' 41 | '*--replace-needed[Replaces a declared dependency on a dynamic library with another one]:LIB_ORIG:_get_dep:LIB_NEW:_files' 42 | '--remove-needed[Removes a declared dependency on LIBRARY]:LIBRARY:_get_dep' 43 | '(- : *)--print-needed[Prints all DT_NEEDED entries of the executable]' 44 | '--no-default-lib[Marks the object so that the search for dependencies of this object will ignore any default library search paths]' 45 | '--no-sort[Do not sort program headers or section headers]' 46 | '--add-debug-tag[Adds DT_DEBUG tag to the .dynamic section if not yet present in an ELF object]' 47 | '(- : *)--print-execstack[Prints the state of the executable flag of the GNU_STACK program header, if present]' 48 | '--clear-execstack[Clears the executable flag of the GNU_STACK program header, or adds a new header]' 49 | '--set-execstack[Sets the executable flag of the GNU_STACK program header, or adds a new header]' 50 | '--rename-dynamic-symbols[Renames dynamic symbols]:NAME_MAP_FILE:_files' 51 | '--output[Set the output file name]:FILE:_files' 52 | '--debug[Prints details of the changes made to the input file]' 53 | '--version[Shows the version of patchelf]' 54 | "(- : *)"{-h,--help}'[Show list of command-line options]' 55 | ) 56 | 57 | _arguments -s -S $options '*: :_files' 58 | -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | AC_PREREQ([2.62]) 2 | AC_INIT([patchelf], m4_esyscmd([printf $(cat ./version)])) 3 | AC_CONFIG_SRCDIR([src/patchelf.cc]) 4 | AC_CONFIG_AUX_DIR([build-aux]) 5 | AM_INIT_AUTOMAKE([1.11.1 -Wall -Werror dist-bzip2 foreign color-tests parallel-tests]) 6 | AC_CONFIG_MACRO_DIR([m4]) 7 | 8 | AC_CHECK_TOOL([STRIP], [strip]) 9 | # Those are only used in tests, hence we gracefully degrate if they are not found. 10 | AC_CHECK_TOOL([NM], [nm], [nm]) 11 | AC_CHECK_TOOL([OBJDUMP], [objdump], [objdump]) 12 | AC_CHECK_TOOL([OBJCOPY], [objcopy], [objcopy]) 13 | AC_CHECK_TOOL([READELF], [readelf], [readelf]) 14 | AC_CHECK_TOOL([STRINGS], [strings], [strings]) 15 | 16 | AM_PROG_CC_C_O 17 | AC_PROG_CXX 18 | AC_LANG([C++]) 19 | AM_PROG_AS 20 | 21 | DEFAULT_PAGESIZE=auto 22 | AC_ARG_WITH([page-size], 23 | AS_HELP_STRING([--with-page-size=SIZE], [Specify default pagesize (default auto)]), 24 | DEFAULT_PAGESIZE=$withval 25 | ) 26 | 27 | if test "$DEFAULT_PAGESIZE" != auto; then 28 | AC_DEFINE_UNQUOTED(DEFAULT_PAGESIZE, ${DEFAULT_PAGESIZE}) 29 | AC_MSG_RESULT([Setting page size to ${DEFAULT_PAGESIZE}]) 30 | fi 31 | 32 | AC_ARG_WITH([asan], 33 | AS_HELP_STRING([--with-asan], [Build with address sanitizer]) 34 | ) 35 | AM_CONDITIONAL([WITH_ASAN], [test x"$with_asan" = xyes]) 36 | 37 | AX_CXX_COMPILE_STDCXX([17], [noext], []) 38 | 39 | AC_ARG_WITH([ubsan], 40 | AS_HELP_STRING([--with-ubsan], [Build with undefined behavior sanitizer]) 41 | ) 42 | AM_CONDITIONAL([WITH_UBSAN], [test x"$with_ubsan" = xyes]) 43 | 44 | AC_CONFIG_FILES([Makefile src/Makefile tests/Makefile patchelf.spec]) 45 | AC_OUTPUT 46 | -------------------------------------------------------------------------------- /default.nix: -------------------------------------------------------------------------------- 1 | (import (fetchTarball https://github.com/edolstra/flake-compat/archive/master.tar.gz) { 2 | src = ./.; 3 | }).defaultNix 4 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "nixpkgs": { 4 | "locked": { 5 | "lastModified": 1731763621, 6 | "narHash": "sha256-ddcX4lQL0X05AYkrkV2LMFgGdRvgap7Ho8kgon3iWZk=", 7 | "owner": "NixOS", 8 | "repo": "nixpkgs", 9 | "rev": "c69a9bffbecde46b4b939465422ddc59493d3e4d", 10 | "type": "github" 11 | }, 12 | "original": { 13 | "owner": "NixOS", 14 | "ref": "nixpkgs-unstable", 15 | "repo": "nixpkgs", 16 | "type": "github" 17 | } 18 | }, 19 | "root": { 20 | "inputs": { 21 | "nixpkgs": "nixpkgs" 22 | } 23 | } 24 | }, 25 | "root": "root", 26 | "version": 7 27 | } 28 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | description = "A tool for modifying ELF executables and libraries"; 3 | 4 | inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; 5 | 6 | outputs = { self, nixpkgs }: 7 | 8 | let 9 | supportedSystems = [ "x86_64-linux" "i686-linux" "aarch64-linux" ]; 10 | forAllSystems = nixpkgs.lib.genAttrs supportedSystems; 11 | 12 | version = nixpkgs.lib.removeSuffix "\n" (builtins.readFile ./version); 13 | pkgs = nixpkgs.legacyPackages.x86_64-linux; 14 | 15 | 16 | patchelfFor = pkgs: let 17 | # this is only 18 | in pkgs.callPackage ./patchelf.nix { 19 | inherit version; 20 | src = self; 21 | }; 22 | 23 | in 24 | 25 | { 26 | overlays.default = final: prev: { 27 | patchelf-new-musl = patchelfFor final.pkgsMusl; 28 | patchelf-new = patchelfFor final; 29 | }; 30 | 31 | hydraJobs = { 32 | tarball = 33 | pkgs.releaseTools.sourceTarball rec { 34 | name = "patchelf-tarball"; 35 | inherit version; 36 | versionSuffix = ""; # obsolete 37 | src = self; 38 | preAutoconf = "echo ${version} > version"; 39 | 40 | # portable configure shouldn't have a shebang pointing to the nix store 41 | postConfigure = '' 42 | sed -i '1s|^.*$|#!/bin/sh|' ./configure 43 | ''; 44 | postDist = '' 45 | cp README.md $out/ 46 | echo "doc readme $out/README.md" >> $out/nix-support/hydra-build-products 47 | ''; 48 | }; 49 | 50 | coverage = 51 | (pkgs.releaseTools.coverageAnalysis { 52 | name = "patchelf-coverage"; 53 | src = self.hydraJobs.tarball; 54 | lcovFilter = ["*/tests/*"]; 55 | }).overrideAttrs (old: { 56 | preCheck = '' 57 | # coverage cflag breaks this target 58 | NIX_CFLAGS_COMPILE=''${NIX_CFLAGS_COMPILE//--coverage} make -C tests phdr-corruption.so 59 | ''; 60 | }); 61 | 62 | build = forAllSystems (system: self.packages.${system}.patchelf); 63 | build-sanitized = forAllSystems (system: self.packages.${system}.patchelf.overrideAttrs (old: { 64 | configureFlags = [ "--with-asan " "--with-ubsan" ]; 65 | # -Wno-unused-command-line-argument is for clang, which does not like 66 | # our cc wrapper arguments 67 | CFLAGS = "-Werror -Wno-unused-command-line-argument"; 68 | })); 69 | 70 | # x86_64-linux seems to be only working clangStdenv at the moment 71 | build-sanitized-clang = nixpkgs.lib.genAttrs [ "x86_64-linux" ] (system: self.hydraJobs.build-sanitized.${system}.override { 72 | stdenv = nixpkgs.legacyPackages.${system}.llvmPackages_latest.libcxxStdenv; 73 | }); 74 | 75 | # To get mingw compiler from hydra cache 76 | inherit (self.packages.x86_64-linux) patchelf-win32 patchelf-win64; 77 | 78 | release = pkgs.releaseTools.aggregate 79 | { name = "patchelf-${self.hydraJobs.tarball.version}"; 80 | constituents = 81 | [ self.hydraJobs.tarball 82 | self.hydraJobs.build.x86_64-linux 83 | self.hydraJobs.build.i686-linux 84 | # FIXME: add aarch64 emulation to our github action... 85 | #self.hydraJobs.build.aarch64-linux 86 | self.hydraJobs.build-sanitized.x86_64-linux 87 | #self.hydraJobs.build-sanitized.aarch64-linux 88 | self.hydraJobs.build-sanitized.i686-linux 89 | self.hydraJobs.build-sanitized-clang.x86_64-linux 90 | ]; 91 | meta.description = "Release-critical builds"; 92 | }; 93 | 94 | }; 95 | 96 | checks = forAllSystems (system: { 97 | build = self.hydraJobs.build.${system}; 98 | }); 99 | 100 | devShells = forAllSystems (system: { 101 | glibc = self.packages.${system}.patchelf; 102 | default = self.devShells.${system}.glibc; 103 | } // nixpkgs.lib.optionalAttrs (system != "i686-linux") { 104 | musl = self.packages.${system}.patchelf-musl; 105 | }); 106 | 107 | packages = forAllSystems (system: let 108 | pkgs = nixpkgs.legacyPackages.${system}; 109 | in { 110 | patchelf = patchelfFor pkgs; 111 | default = self.packages.${system}.patchelf; 112 | 113 | # This is a good test to see if packages can be cross-compiled. It also 114 | # tests if our testsuite uses target-prefixed executable names. 115 | patchelf-musl-cross = patchelfFor pkgs.pkgsCross.musl64; 116 | patchelf-netbsd-cross = patchelfFor pkgs.pkgsCross.x86_64-netbsd; 117 | 118 | patchelf-win32 = (patchelfFor pkgs.pkgsCross.mingw32).overrideAttrs (old: { 119 | NIX_CFLAGS_COMPILE = "-static"; 120 | }); 121 | patchelf-win64 = (patchelfFor pkgs.pkgsCross.mingwW64).overrideAttrs (old: { 122 | NIX_CFLAGS_COMPILE = "-static"; 123 | }); 124 | } // nixpkgs.lib.optionalAttrs (system != "i686-linux") { 125 | patchelf-musl = patchelfFor nixpkgs.legacyPackages.${system}.pkgsMusl; 126 | }); 127 | 128 | }; 129 | } 130 | -------------------------------------------------------------------------------- /m4/ax_cxx_compile_stdcxx.m4: -------------------------------------------------------------------------------- 1 | # =========================================================================== 2 | # https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx.html 3 | # =========================================================================== 4 | # 5 | # SYNOPSIS 6 | # 7 | # AX_CXX_COMPILE_STDCXX(VERSION, [ext|noext], [mandatory|optional]) 8 | # 9 | # DESCRIPTION 10 | # 11 | # Check for baseline language coverage in the compiler for the specified 12 | # version of the C++ standard. If necessary, add switches to CXX and 13 | # CXXCPP to enable support. VERSION may be '11', '14', '17', or '20' for 14 | # the respective C++ standard version. 15 | # 16 | # The second argument, if specified, indicates whether you insist on an 17 | # extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. 18 | # -std=c++11). If neither is specified, you get whatever works, with 19 | # preference for no added switch, and then for an extended mode. 20 | # 21 | # The third argument, if specified 'mandatory' or if left unspecified, 22 | # indicates that baseline support for the specified C++ standard is 23 | # required and that the macro should error out if no mode with that 24 | # support is found. If specified 'optional', then configuration proceeds 25 | # regardless, after defining HAVE_CXX${VERSION} if and only if a 26 | # supporting mode is found. 27 | # 28 | # LICENSE 29 | # 30 | # Copyright (c) 2008 Benjamin Kosnik <bkoz@redhat.com> 31 | # Copyright (c) 2012 Zack Weinberg <zackw@panix.com> 32 | # Copyright (c) 2013 Roy Stogner <roystgnr@ices.utexas.edu> 33 | # Copyright (c) 2014, 2015 Google Inc.; contributed by Alexey Sokolov <sokolov@google.com> 34 | # Copyright (c) 2015 Paul Norman <penorman@mac.com> 35 | # Copyright (c) 2015 Moritz Klammler <moritz@klammler.eu> 36 | # Copyright (c) 2016, 2018 Krzesimir Nowak <qdlacz@gmail.com> 37 | # Copyright (c) 2019 Enji Cooper <yaneurabeya@gmail.com> 38 | # Copyright (c) 2020 Jason Merrill <jason@redhat.com> 39 | # Copyright (c) 2021 Jörn Heusipp <osmanx@problemloesungsmaschine.de> 40 | # 41 | # Copying and distribution of this file, with or without modification, are 42 | # permitted in any medium without royalty provided the copyright notice 43 | # and this notice are preserved. This file is offered as-is, without any 44 | # warranty. 45 | 46 | #serial 15 47 | 48 | dnl This macro is based on the code from the AX_CXX_COMPILE_STDCXX_11 macro 49 | dnl (serial version number 13). 50 | 51 | AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl 52 | m4_if([$1], [11], [ax_cxx_compile_alternatives="11 0x"], 53 | [$1], [14], [ax_cxx_compile_alternatives="14 1y"], 54 | [$1], [17], [ax_cxx_compile_alternatives="17 1z"], 55 | [$1], [20], [ax_cxx_compile_alternatives="20"], 56 | [m4_fatal([invalid first argument `$1' to AX_CXX_COMPILE_STDCXX])])dnl 57 | m4_if([$2], [], [], 58 | [$2], [ext], [], 59 | [$2], [noext], [], 60 | [m4_fatal([invalid second argument `$2' to AX_CXX_COMPILE_STDCXX])])dnl 61 | m4_if([$3], [], [ax_cxx_compile_cxx$1_required=true], 62 | [$3], [mandatory], [ax_cxx_compile_cxx$1_required=true], 63 | [$3], [optional], [ax_cxx_compile_cxx$1_required=false], 64 | [m4_fatal([invalid third argument `$3' to AX_CXX_COMPILE_STDCXX])]) 65 | AC_LANG_PUSH([C++])dnl 66 | ac_success=no 67 | 68 | m4_if([$2], [], [dnl 69 | AC_CACHE_CHECK(whether $CXX supports C++$1 features by default, 70 | ax_cv_cxx_compile_cxx$1, 71 | [AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], 72 | [ax_cv_cxx_compile_cxx$1=yes], 73 | [ax_cv_cxx_compile_cxx$1=no])]) 74 | if test x$ax_cv_cxx_compile_cxx$1 = xyes; then 75 | ac_success=yes 76 | fi]) 77 | 78 | m4_if([$2], [noext], [], [dnl 79 | if test x$ac_success = xno; then 80 | for alternative in ${ax_cxx_compile_alternatives}; do 81 | switch="-std=gnu++${alternative}" 82 | cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) 83 | AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, 84 | $cachevar, 85 | [ac_save_CXX="$CXX" 86 | CXX="$CXX $switch" 87 | AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], 88 | [eval $cachevar=yes], 89 | [eval $cachevar=no]) 90 | CXX="$ac_save_CXX"]) 91 | if eval test x\$cachevar = xyes; then 92 | CXX="$CXX $switch" 93 | if test -n "$CXXCPP" ; then 94 | CXXCPP="$CXXCPP $switch" 95 | fi 96 | ac_success=yes 97 | break 98 | fi 99 | done 100 | fi]) 101 | 102 | m4_if([$2], [ext], [], [dnl 103 | if test x$ac_success = xno; then 104 | dnl HP's aCC needs +std=c++11 according to: 105 | dnl http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/PDF_Release_Notes/769149-001.pdf 106 | dnl Cray's crayCC needs "-h std=c++11" 107 | for alternative in ${ax_cxx_compile_alternatives}; do 108 | for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do 109 | cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) 110 | AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, 111 | $cachevar, 112 | [ac_save_CXX="$CXX" 113 | CXX="$CXX $switch" 114 | AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], 115 | [eval $cachevar=yes], 116 | [eval $cachevar=no]) 117 | CXX="$ac_save_CXX"]) 118 | if eval test x\$cachevar = xyes; then 119 | CXX="$CXX $switch" 120 | if test -n "$CXXCPP" ; then 121 | CXXCPP="$CXXCPP $switch" 122 | fi 123 | ac_success=yes 124 | break 125 | fi 126 | done 127 | if test x$ac_success = xyes; then 128 | break 129 | fi 130 | done 131 | fi]) 132 | AC_LANG_POP([C++]) 133 | if test x$ax_cxx_compile_cxx$1_required = xtrue; then 134 | if test x$ac_success = xno; then 135 | AC_MSG_ERROR([*** A compiler with support for C++$1 language features is required.]) 136 | fi 137 | fi 138 | if test x$ac_success = xno; then 139 | HAVE_CXX$1=0 140 | AC_MSG_NOTICE([No compiler with C++$1 support was found]) 141 | else 142 | HAVE_CXX$1=1 143 | AC_DEFINE(HAVE_CXX$1,1, 144 | [define if the compiler supports basic C++$1 syntax]) 145 | fi 146 | AC_SUBST(HAVE_CXX$1) 147 | ]) 148 | 149 | 150 | dnl Test body for checking C++11 support 151 | 152 | m4_define([_AX_CXX_COMPILE_STDCXX_testbody_11], 153 | _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 154 | ) 155 | 156 | dnl Test body for checking C++14 support 157 | 158 | m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14], 159 | _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 160 | _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 161 | ) 162 | 163 | dnl Test body for checking C++17 support 164 | 165 | m4_define([_AX_CXX_COMPILE_STDCXX_testbody_17], 166 | _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 167 | _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 168 | _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 169 | ) 170 | 171 | dnl Test body for checking C++20 support 172 | 173 | m4_define([_AX_CXX_COMPILE_STDCXX_testbody_20], 174 | _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 175 | _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 176 | _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 177 | _AX_CXX_COMPILE_STDCXX_testbody_new_in_20 178 | ) 179 | 180 | 181 | dnl Tests for new features in C++11 182 | 183 | m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[ 184 | 185 | // If the compiler admits that it is not ready for C++11, why torture it? 186 | // Hopefully, this will speed up the test. 187 | 188 | #ifndef __cplusplus 189 | 190 | #error "This is not a C++ compiler" 191 | 192 | // MSVC always sets __cplusplus to 199711L in older versions; newer versions 193 | // only set it correctly if /Zc:__cplusplus is specified as well as a 194 | // /std:c++NN switch: 195 | // https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/ 196 | #elif __cplusplus < 201103L && !defined _MSC_VER 197 | 198 | #error "This is not a C++11 compiler" 199 | 200 | #else 201 | 202 | namespace cxx11 203 | { 204 | 205 | namespace test_static_assert 206 | { 207 | 208 | template <typename T> 209 | struct check 210 | { 211 | static_assert(sizeof(int) <= sizeof(T), "not big enough"); 212 | }; 213 | 214 | } 215 | 216 | namespace test_final_override 217 | { 218 | 219 | struct Base 220 | { 221 | virtual ~Base() {} 222 | virtual void f() {} 223 | }; 224 | 225 | struct Derived : public Base 226 | { 227 | virtual ~Derived() override {} 228 | virtual void f() override {} 229 | }; 230 | 231 | } 232 | 233 | namespace test_double_right_angle_brackets 234 | { 235 | 236 | template < typename T > 237 | struct check {}; 238 | 239 | typedef check<void> single_type; 240 | typedef check<check<void>> double_type; 241 | typedef check<check<check<void>>> triple_type; 242 | typedef check<check<check<check<void>>>> quadruple_type; 243 | 244 | } 245 | 246 | namespace test_decltype 247 | { 248 | 249 | int 250 | f() 251 | { 252 | int a = 1; 253 | decltype(a) b = 2; 254 | return a + b; 255 | } 256 | 257 | } 258 | 259 | namespace test_type_deduction 260 | { 261 | 262 | template < typename T1, typename T2 > 263 | struct is_same 264 | { 265 | static const bool value = false; 266 | }; 267 | 268 | template < typename T > 269 | struct is_same<T, T> 270 | { 271 | static const bool value = true; 272 | }; 273 | 274 | template < typename T1, typename T2 > 275 | auto 276 | add(T1 a1, T2 a2) -> decltype(a1 + a2) 277 | { 278 | return a1 + a2; 279 | } 280 | 281 | int 282 | test(const int c, volatile int v) 283 | { 284 | static_assert(is_same<int, decltype(0)>::value == true, ""); 285 | static_assert(is_same<int, decltype(c)>::value == false, ""); 286 | static_assert(is_same<int, decltype(v)>::value == false, ""); 287 | auto ac = c; 288 | auto av = v; 289 | auto sumi = ac + av + 'x'; 290 | auto sumf = ac + av + 1.0; 291 | static_assert(is_same<int, decltype(ac)>::value == true, ""); 292 | static_assert(is_same<int, decltype(av)>::value == true, ""); 293 | static_assert(is_same<int, decltype(sumi)>::value == true, ""); 294 | static_assert(is_same<int, decltype(sumf)>::value == false, ""); 295 | static_assert(is_same<int, decltype(add(c, v))>::value == true, ""); 296 | return (sumf > 0.0) ? sumi : add(c, v); 297 | } 298 | 299 | } 300 | 301 | namespace test_noexcept 302 | { 303 | 304 | int f() { return 0; } 305 | int g() noexcept { return 0; } 306 | 307 | static_assert(noexcept(f()) == false, ""); 308 | static_assert(noexcept(g()) == true, ""); 309 | 310 | } 311 | 312 | namespace test_constexpr 313 | { 314 | 315 | template < typename CharT > 316 | unsigned long constexpr 317 | strlen_c_r(const CharT *const s, const unsigned long acc) noexcept 318 | { 319 | return *s ? strlen_c_r(s + 1, acc + 1) : acc; 320 | } 321 | 322 | template < typename CharT > 323 | unsigned long constexpr 324 | strlen_c(const CharT *const s) noexcept 325 | { 326 | return strlen_c_r(s, 0UL); 327 | } 328 | 329 | static_assert(strlen_c("") == 0UL, ""); 330 | static_assert(strlen_c("1") == 1UL, ""); 331 | static_assert(strlen_c("example") == 7UL, ""); 332 | static_assert(strlen_c("another\0example") == 7UL, ""); 333 | 334 | } 335 | 336 | namespace test_rvalue_references 337 | { 338 | 339 | template < int N > 340 | struct answer 341 | { 342 | static constexpr int value = N; 343 | }; 344 | 345 | answer<1> f(int&) { return answer<1>(); } 346 | answer<2> f(const int&) { return answer<2>(); } 347 | answer<3> f(int&&) { return answer<3>(); } 348 | 349 | void 350 | test() 351 | { 352 | int i = 0; 353 | const int c = 0; 354 | static_assert(decltype(f(i))::value == 1, ""); 355 | static_assert(decltype(f(c))::value == 2, ""); 356 | static_assert(decltype(f(0))::value == 3, ""); 357 | } 358 | 359 | } 360 | 361 | namespace test_uniform_initialization 362 | { 363 | 364 | struct test 365 | { 366 | static const int zero {}; 367 | static const int one {1}; 368 | }; 369 | 370 | static_assert(test::zero == 0, ""); 371 | static_assert(test::one == 1, ""); 372 | 373 | } 374 | 375 | namespace test_lambdas 376 | { 377 | 378 | void 379 | test1() 380 | { 381 | auto lambda1 = [](){}; 382 | auto lambda2 = lambda1; 383 | lambda1(); 384 | lambda2(); 385 | } 386 | 387 | int 388 | test2() 389 | { 390 | auto a = [](int i, int j){ return i + j; }(1, 2); 391 | auto b = []() -> int { return '0'; }(); 392 | auto c = [=](){ return a + b; }(); 393 | auto d = [&](){ return c; }(); 394 | auto e = [a, &b](int x) mutable { 395 | const auto identity = [](int y){ return y; }; 396 | for (auto i = 0; i < a; ++i) 397 | a += b--; 398 | return x + identity(a + b); 399 | }(0); 400 | return a + b + c + d + e; 401 | } 402 | 403 | int 404 | test3() 405 | { 406 | const auto nullary = [](){ return 0; }; 407 | const auto unary = [](int x){ return x; }; 408 | using nullary_t = decltype(nullary); 409 | using unary_t = decltype(unary); 410 | const auto higher1st = [](nullary_t f){ return f(); }; 411 | const auto higher2nd = [unary](nullary_t f1){ 412 | return [unary, f1](unary_t f2){ return f2(unary(f1())); }; 413 | }; 414 | return higher1st(nullary) + higher2nd(nullary)(unary); 415 | } 416 | 417 | } 418 | 419 | namespace test_variadic_templates 420 | { 421 | 422 | template <int...> 423 | struct sum; 424 | 425 | template <int N0, int... N1toN> 426 | struct sum<N0, N1toN...> 427 | { 428 | static constexpr auto value = N0 + sum<N1toN...>::value; 429 | }; 430 | 431 | template <> 432 | struct sum<> 433 | { 434 | static constexpr auto value = 0; 435 | }; 436 | 437 | static_assert(sum<>::value == 0, ""); 438 | static_assert(sum<1>::value == 1, ""); 439 | static_assert(sum<23>::value == 23, ""); 440 | static_assert(sum<1, 2>::value == 3, ""); 441 | static_assert(sum<5, 5, 11>::value == 21, ""); 442 | static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, ""); 443 | 444 | } 445 | 446 | // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae 447 | // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function 448 | // because of this. 449 | namespace test_template_alias_sfinae 450 | { 451 | 452 | struct foo {}; 453 | 454 | template<typename T> 455 | using member = typename T::member_type; 456 | 457 | template<typename T> 458 | void func(...) {} 459 | 460 | template<typename T> 461 | void func(member<T>*) {} 462 | 463 | void test(); 464 | 465 | void test() { func<foo>(0); } 466 | 467 | } 468 | 469 | } // namespace cxx11 470 | 471 | #endif // __cplusplus >= 201103L 472 | 473 | ]]) 474 | 475 | 476 | dnl Tests for new features in C++14 477 | 478 | m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_14], [[ 479 | 480 | // If the compiler admits that it is not ready for C++14, why torture it? 481 | // Hopefully, this will speed up the test. 482 | 483 | #ifndef __cplusplus 484 | 485 | #error "This is not a C++ compiler" 486 | 487 | #elif __cplusplus < 201402L && !defined _MSC_VER 488 | 489 | #error "This is not a C++14 compiler" 490 | 491 | #else 492 | 493 | namespace cxx14 494 | { 495 | 496 | namespace test_polymorphic_lambdas 497 | { 498 | 499 | int 500 | test() 501 | { 502 | const auto lambda = [](auto&&... args){ 503 | const auto istiny = [](auto x){ 504 | return (sizeof(x) == 1UL) ? 1 : 0; 505 | }; 506 | const int aretiny[] = { istiny(args)... }; 507 | return aretiny[0]; 508 | }; 509 | return lambda(1, 1L, 1.0f, '1'); 510 | } 511 | 512 | } 513 | 514 | namespace test_binary_literals 515 | { 516 | 517 | constexpr auto ivii = 0b0000000000101010; 518 | static_assert(ivii == 42, "wrong value"); 519 | 520 | } 521 | 522 | namespace test_generalized_constexpr 523 | { 524 | 525 | template < typename CharT > 526 | constexpr unsigned long 527 | strlen_c(const CharT *const s) noexcept 528 | { 529 | auto length = 0UL; 530 | for (auto p = s; *p; ++p) 531 | ++length; 532 | return length; 533 | } 534 | 535 | static_assert(strlen_c("") == 0UL, ""); 536 | static_assert(strlen_c("x") == 1UL, ""); 537 | static_assert(strlen_c("test") == 4UL, ""); 538 | static_assert(strlen_c("another\0test") == 7UL, ""); 539 | 540 | } 541 | 542 | namespace test_lambda_init_capture 543 | { 544 | 545 | int 546 | test() 547 | { 548 | auto x = 0; 549 | const auto lambda1 = [a = x](int b){ return a + b; }; 550 | const auto lambda2 = [a = lambda1(x)](){ return a; }; 551 | return lambda2(); 552 | } 553 | 554 | } 555 | 556 | namespace test_digit_separators 557 | { 558 | 559 | constexpr auto ten_million = 100'000'000; 560 | static_assert(ten_million == 100000000, ""); 561 | 562 | } 563 | 564 | namespace test_return_type_deduction 565 | { 566 | 567 | auto f(int& x) { return x; } 568 | decltype(auto) g(int& x) { return x; } 569 | 570 | template < typename T1, typename T2 > 571 | struct is_same 572 | { 573 | static constexpr auto value = false; 574 | }; 575 | 576 | template < typename T > 577 | struct is_same<T, T> 578 | { 579 | static constexpr auto value = true; 580 | }; 581 | 582 | int 583 | test() 584 | { 585 | auto x = 0; 586 | static_assert(is_same<int, decltype(f(x))>::value, ""); 587 | static_assert(is_same<int&, decltype(g(x))>::value, ""); 588 | return x; 589 | } 590 | 591 | } 592 | 593 | } // namespace cxx14 594 | 595 | #endif // __cplusplus >= 201402L 596 | 597 | ]]) 598 | 599 | 600 | dnl Tests for new features in C++17 601 | 602 | m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_17], [[ 603 | 604 | // If the compiler admits that it is not ready for C++17, why torture it? 605 | // Hopefully, this will speed up the test. 606 | 607 | #ifndef __cplusplus 608 | 609 | #error "This is not a C++ compiler" 610 | 611 | #elif __cplusplus < 201703L && !defined _MSC_VER 612 | 613 | #error "This is not a C++17 compiler" 614 | 615 | #else 616 | 617 | #include <initializer_list> 618 | #include <utility> 619 | #include <type_traits> 620 | 621 | namespace cxx17 622 | { 623 | 624 | namespace test_constexpr_lambdas 625 | { 626 | 627 | constexpr int foo = [](){return 42;}(); 628 | 629 | } 630 | 631 | namespace test::nested_namespace::definitions 632 | { 633 | 634 | } 635 | 636 | namespace test_fold_expression 637 | { 638 | 639 | template<typename... Args> 640 | int multiply(Args... args) 641 | { 642 | return (args * ... * 1); 643 | } 644 | 645 | template<typename... Args> 646 | bool all(Args... args) 647 | { 648 | return (args && ...); 649 | } 650 | 651 | } 652 | 653 | namespace test_extended_static_assert 654 | { 655 | 656 | static_assert (true); 657 | 658 | } 659 | 660 | namespace test_auto_brace_init_list 661 | { 662 | 663 | auto foo = {5}; 664 | auto bar {5}; 665 | 666 | static_assert(std::is_same<std::initializer_list<int>, decltype(foo)>::value); 667 | static_assert(std::is_same<int, decltype(bar)>::value); 668 | } 669 | 670 | namespace test_typename_in_template_template_parameter 671 | { 672 | 673 | template<template<typename> typename X> struct D; 674 | 675 | } 676 | 677 | namespace test_fallthrough_nodiscard_maybe_unused_attributes 678 | { 679 | 680 | int f1() 681 | { 682 | return 42; 683 | } 684 | 685 | [[nodiscard]] int f2() 686 | { 687 | [[maybe_unused]] auto unused = f1(); 688 | 689 | switch (f1()) 690 | { 691 | case 17: 692 | f1(); 693 | [[fallthrough]]; 694 | case 42: 695 | f1(); 696 | } 697 | return f1(); 698 | } 699 | 700 | } 701 | 702 | namespace test_extended_aggregate_initialization 703 | { 704 | 705 | struct base1 706 | { 707 | int b1, b2 = 42; 708 | }; 709 | 710 | struct base2 711 | { 712 | base2() { 713 | b3 = 42; 714 | } 715 | int b3; 716 | }; 717 | 718 | struct derived : base1, base2 719 | { 720 | int d; 721 | }; 722 | 723 | derived d1 {{1, 2}, {}, 4}; // full initialization 724 | derived d2 {{}, {}, 4}; // value-initialized bases 725 | 726 | } 727 | 728 | namespace test_general_range_based_for_loop 729 | { 730 | 731 | struct iter 732 | { 733 | int i; 734 | 735 | int& operator* () 736 | { 737 | return i; 738 | } 739 | 740 | const int& operator* () const 741 | { 742 | return i; 743 | } 744 | 745 | iter& operator++() 746 | { 747 | ++i; 748 | return *this; 749 | } 750 | }; 751 | 752 | struct sentinel 753 | { 754 | int i; 755 | }; 756 | 757 | bool operator== (const iter& i, const sentinel& s) 758 | { 759 | return i.i == s.i; 760 | } 761 | 762 | bool operator!= (const iter& i, const sentinel& s) 763 | { 764 | return !(i == s); 765 | } 766 | 767 | struct range 768 | { 769 | iter begin() const 770 | { 771 | return {0}; 772 | } 773 | 774 | sentinel end() const 775 | { 776 | return {5}; 777 | } 778 | }; 779 | 780 | void f() 781 | { 782 | range r {}; 783 | 784 | for (auto i : r) 785 | { 786 | [[maybe_unused]] auto v = i; 787 | } 788 | } 789 | 790 | } 791 | 792 | namespace test_lambda_capture_asterisk_this_by_value 793 | { 794 | 795 | struct t 796 | { 797 | int i; 798 | int foo() 799 | { 800 | return [*this]() 801 | { 802 | return i; 803 | }(); 804 | } 805 | }; 806 | 807 | } 808 | 809 | namespace test_enum_class_construction 810 | { 811 | 812 | enum class byte : unsigned char 813 | {}; 814 | 815 | byte foo {42}; 816 | 817 | } 818 | 819 | namespace test_constexpr_if 820 | { 821 | 822 | template <bool cond> 823 | int f () 824 | { 825 | if constexpr(cond) 826 | { 827 | return 13; 828 | } 829 | else 830 | { 831 | return 42; 832 | } 833 | } 834 | 835 | } 836 | 837 | namespace test_selection_statement_with_initializer 838 | { 839 | 840 | int f() 841 | { 842 | return 13; 843 | } 844 | 845 | int f2() 846 | { 847 | if (auto i = f(); i > 0) 848 | { 849 | return 3; 850 | } 851 | 852 | switch (auto i = f(); i + 4) 853 | { 854 | case 17: 855 | return 2; 856 | 857 | default: 858 | return 1; 859 | } 860 | } 861 | 862 | } 863 | 864 | namespace test_template_argument_deduction_for_class_templates 865 | { 866 | 867 | template <typename T1, typename T2> 868 | struct pair 869 | { 870 | pair (T1 p1, T2 p2) 871 | : m1 {p1}, 872 | m2 {p2} 873 | {} 874 | 875 | T1 m1; 876 | T2 m2; 877 | }; 878 | 879 | void f() 880 | { 881 | [[maybe_unused]] auto p = pair{13, 42u}; 882 | } 883 | 884 | } 885 | 886 | namespace test_non_type_auto_template_parameters 887 | { 888 | 889 | template <auto n> 890 | struct B 891 | {}; 892 | 893 | B<5> b1; 894 | B<'a'> b2; 895 | 896 | } 897 | 898 | namespace test_structured_bindings 899 | { 900 | 901 | int arr[2] = { 1, 2 }; 902 | std::pair<int, int> pr = { 1, 2 }; 903 | 904 | auto f1() -> int(&)[2] 905 | { 906 | return arr; 907 | } 908 | 909 | auto f2() -> std::pair<int, int>& 910 | { 911 | return pr; 912 | } 913 | 914 | struct S 915 | { 916 | int x1 : 2; 917 | volatile double y1; 918 | }; 919 | 920 | S f3() 921 | { 922 | return {}; 923 | } 924 | 925 | auto [ x1, y1 ] = f1(); 926 | auto& [ xr1, yr1 ] = f1(); 927 | auto [ x2, y2 ] = f2(); 928 | auto& [ xr2, yr2 ] = f2(); 929 | const auto [ x3, y3 ] = f3(); 930 | 931 | } 932 | 933 | namespace test_exception_spec_type_system 934 | { 935 | 936 | struct Good {}; 937 | struct Bad {}; 938 | 939 | void g1() noexcept; 940 | void g2(); 941 | 942 | template<typename T> 943 | Bad 944 | f(T*, T*); 945 | 946 | template<typename T1, typename T2> 947 | Good 948 | f(T1*, T2*); 949 | 950 | static_assert (std::is_same_v<Good, decltype(f(g1, g2))>); 951 | 952 | } 953 | 954 | namespace test_inline_variables 955 | { 956 | 957 | template<class T> void f(T) 958 | {} 959 | 960 | template<class T> inline T g(T) 961 | { 962 | return T{}; 963 | } 964 | 965 | template<> inline void f<>(int) 966 | {} 967 | 968 | template<> int g<>(int) 969 | { 970 | return 5; 971 | } 972 | 973 | } 974 | 975 | } // namespace cxx17 976 | 977 | #endif // __cplusplus < 201703L && !defined _MSC_VER 978 | 979 | ]]) 980 | 981 | 982 | dnl Tests for new features in C++20 983 | 984 | m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_20], [[ 985 | 986 | #ifndef __cplusplus 987 | 988 | #error "This is not a C++ compiler" 989 | 990 | #elif __cplusplus < 202002L && !defined _MSC_VER 991 | 992 | #error "This is not a C++20 compiler" 993 | 994 | #else 995 | 996 | #include <version> 997 | 998 | namespace cxx20 999 | { 1000 | 1001 | // As C++20 supports feature test macros in the standard, there is no 1002 | // immediate need to actually test for feature availability on the 1003 | // Autoconf side. 1004 | 1005 | } // namespace cxx20 1006 | 1007 | #endif // __cplusplus < 202002L && !defined _MSC_VER 1008 | 1009 | ]]) 1010 | -------------------------------------------------------------------------------- /patchelf.1: -------------------------------------------------------------------------------- 1 | .\" Process this file with 2 | .\" groff -man -Tascii patchelf.1 3 | .\" 4 | .TH PATCHELF 1 "JULY 2022" PATCHELF "User Manuals" 5 | .SH NAME 6 | patchelf - Modify ELF files 7 | 8 | .SH SYNOPSIS 9 | .B patchelf 10 | .I OPTION 11 | .B 12 | .I FILE 13 | .SM ... 14 | .B 15 | 16 | .SH DESCRIPTION 17 | 18 | PatchELF is a simple utility for modifying existing ELF executables 19 | and libraries. It can change the dynamic loader ("ELF interpreter") 20 | of executables and change the RPATH of executables and libraries. 21 | 22 | .SH OPTIONS 23 | 24 | The single option given operates on each FILE, editing in place. 25 | 26 | Any option taking a string argument can also take a file by prefixing the 27 | argument with the @ symbol. See EXAMPLES 28 | 29 | .IP "--page-size SIZE" 30 | Uses the given page size instead of the default. 31 | 32 | .IP "--set-interpreter INTERPRETER" 33 | Change the dynamic loader ("ELF interpreter") of executable given to 34 | INTERPRETER. 35 | 36 | .IP --print-interpreter 37 | Prints the ELF interpreter of the executable. 38 | 39 | .IP --print-os-abi 40 | Prints the OS ABI of the executable (EI_OSABI field of an ELF file). 41 | 42 | .IP "--set-os-abi ABI" 43 | Changes the OS ABI of the executable (EI_OSABI field of an ELF file). 44 | The ABI parameter is pretty flexible. For example, you can specify it 45 | as a "Linux", "linux", or even "lInUx" - all those names will set EI_OSABI 46 | field of the ELF header to the value "3", which corresponds to Linux OS ABI. 47 | The same applies to other ABI names - System V, FreeBSD, Solaris, etc. 48 | 49 | .IP --print-soname 50 | Prints DT_SONAME entry of .dynamic section. 51 | Raises an error if DT_SONAME doesn't exist. 52 | 53 | .IP "--set-soname SONAME" 54 | Sets DT_SONAME entry of a library to SONAME. 55 | 56 | .IP "--set-rpath RUNPATH" 57 | Change the DT_RUNPATH of the executable or library to RUNPATH. 58 | 59 | .IP "--add-rpath RUNPATH" 60 | Add RUNPATH to the existing DT_RUNPATH of the executable or library. 61 | 62 | .IP --remove-rpath 63 | Removes the DT_RPATH or DT_RUNPATH entry of the executable or library. 64 | 65 | .IP --shrink-rpath 66 | Remove from the DT_RUNPATH or DT_RPATH all directories that do not contain a 67 | library referenced by DT_NEEDED fields of the executable or library. 68 | 69 | For instance, if an executable references one library libfoo.so, has 70 | an RPATH "/lib:/usr/lib:/foo/lib", and libfoo.so can only be found 71 | in /foo/lib, then the new RPATH will be "/foo/lib". 72 | 73 | .IP "--allowed-rpath-prefixes PREFIXES" 74 | Combined with the "--shrink-rpath" option, this can be used for 75 | further rpath tuning. For instance, if an executable has an RPATH 76 | "/tmp/build-foo/.libs:/foo/lib", it is probably desirable to keep 77 | the "/foo/lib" reference instead of the "/tmp" entry. 78 | 79 | .IP --print-rpath 80 | Prints the DT_RUNPATH or DT_RPATH for an executable or library. 81 | 82 | .IP --force-rpath 83 | Forces the use of the obsolete DT_RPATH in the file instead of 84 | DT_RUNPATH. By default DT_RPATH is converted to DT_RUNPATH. 85 | 86 | .IP "--add-needed LIBRARY" 87 | Adds a declared dependency on a dynamic library (DT_NEEDED). 88 | This option can be given multiple times. 89 | 90 | .IP "--replace-needed LIB_ORIG LIB_NEW" 91 | Replaces a declared dependency on a dynamic library with another one (DT_NEEDED). 92 | This option can be given multiple times. 93 | 94 | .IP "--remove-needed LIBRARY" 95 | Removes a declared dependency on LIBRARY (DT_NEEDED entry). This 96 | option can be given multiple times. 97 | 98 | .IP --print-needed 99 | Prints all DT_NEEDED entries of the executable. 100 | 101 | .IP "--no-default-lib" 102 | Marks the object so that the search for dependencies of this object will ignore any 103 | default library search paths. 104 | 105 | .IP "--no-sort" 106 | Do not sort program headers or section headers. This is useful when 107 | debugging patchelf, because it makes it easier to read diffs of the 108 | output of "readelf -a". 109 | 110 | .IP "--add-debug-tag" 111 | Adds DT_DEBUG tag to the .dynamic section if not yet present in an ELF 112 | object. A shared library (-shared) by default does not receive DT_DEBUG tag. 113 | This means that when a shared library has an entry point (so that it 114 | can be run as an executable), the debugger does not connect to it correctly and 115 | symbols are not resolved. 116 | 117 | .IP "--print-execstack" 118 | Prints the state of the executable flag of the GNU_STACK program header, if present. 119 | 120 | .IP "--clear-execstack" 121 | Clears the executable flag of the GNU_STACK program header, or adds a new header. 122 | 123 | .IP "--set-execstack" 124 | Sets the executable flag of the GNU_STACK program header, or adds a new header. 125 | 126 | .IP "--rename-dynamic-symbols NAME_MAP_FILE" 127 | Renames dynamic symbols. The name map file should contain lines 128 | with the old and the new name separated by spaces like this: 129 | 130 | old_name new_name 131 | 132 | Symbol names do not contain version specifier that are also shown in the output of the nm -D command from binutils. So instead of the name write@GLIBC_2.2.5 it is just write. 133 | 134 | .IP "--no-clobber-old-sections" 135 | Do not clobber old section values. 136 | 137 | patchelf defaults to overwriting replaced header sections with garbage to ensure they are not 138 | used accidentally. This option allows to opt out of that behavior, so that binaries that attempt 139 | to read their own headers from a fixed offset (e.g. Firefox) continue working. 140 | 141 | Use sparingly and with caution. 142 | 143 | .IP "--output FILE" 144 | Set the output file name. If not specified, the input will be modified in place. 145 | 146 | .IP --debug 147 | Prints details of the changes made to the input file. 148 | 149 | .IP --version 150 | Shows the version of patchelf. 151 | 152 | .SH EXAMPLES 153 | 154 | To use the contents on an external file as a parameter: 155 | 156 | .RS 157 | $ patchelf a.out --add-rpath @/tmp/generated-rpath.bin 158 | .RE 159 | 160 | To change the RPATH of a binary. Note that 161 | .BR $ORIGIN 162 | is a special symbol used by the loader, so must be quoted. 163 | 164 | .RS 165 | patchelf --set-rpath '$ORIGIN/../lib64' a.out 166 | .RE 167 | 168 | 169 | .SH AUTHOR 170 | Eelco Dolstra <e.dolstra@tudelft.nl> 171 | 172 | .SH "SEE ALSO" 173 | .BR elf (5), 174 | .BR ld.so (8) 175 | 176 | 177 | -------------------------------------------------------------------------------- /patchelf.nix: -------------------------------------------------------------------------------- 1 | { stdenv, buildPackages, autoreconfHook, version, src, overrideCC }: 2 | let 3 | # on windows we use win32 threads to get a fully static binary 4 | gcc = buildPackages.wrapCC (buildPackages.gcc-unwrapped.override ({ 5 | threadsCross = { 6 | model = "win32"; 7 | package = null; 8 | }; 9 | })); 10 | 11 | stdenv' = if (stdenv.cc.isGNU && stdenv.targetPlatform.isWindows) then 12 | overrideCC stdenv gcc 13 | else 14 | stdenv; 15 | in 16 | stdenv'.mkDerivation { 17 | pname = "patchelf"; 18 | inherit version src; 19 | nativeBuildInputs = [ autoreconfHook ]; 20 | doCheck = true; 21 | } 22 | -------------------------------------------------------------------------------- /patchelf.spec.in: -------------------------------------------------------------------------------- 1 | Summary: A utility for patching ELF binaries 2 | 3 | Name: patchelf 4 | Version: @PACKAGE_VERSION@ 5 | Release: 1 6 | License: GPL 7 | Group: Development/Tools 8 | URL: http://nixos.org/patchelf.html 9 | Source0: %{name}-%{version}.tar.bz2 10 | BuildRoot: %{_tmppath}/%{name}-%{version}-buildroot 11 | Prefix: /usr 12 | 13 | %description 14 | 15 | PatchELF is a simple utility for modifying existing ELF executables and 16 | libraries. It can change the dynamic loader ("ELF interpreter") of 17 | executables and change the RPATH of executables and libraries. 18 | 19 | %prep 20 | %setup -q 21 | 22 | %build 23 | ./configure --prefix=%{_prefix} 24 | make 25 | make check 26 | 27 | %install 28 | rm -rf $RPM_BUILD_ROOT 29 | make DESTDIR=$RPM_BUILD_ROOT install 30 | # rpmbuild automatically strips... strip $RPM_BUILD_ROOT/%%{_bindir}/* || true 31 | 32 | %clean 33 | rm -rf $RPM_BUILD_ROOT 34 | 35 | %files 36 | %{_bindir}/patchelf 37 | %doc %{_docdir}/patchelf/README.md 38 | %{_mandir}/man1/patchelf.1.gz 39 | %{_datadir}/zsh/site-functions/_patchelf 40 | -------------------------------------------------------------------------------- /src/Makefile.am: -------------------------------------------------------------------------------- 1 | AM_CXXFLAGS = -Wall -Wextra -Wcast-qual -std=c++17 -D_FILE_OFFSET_BITS=64 2 | 3 | if WITH_ASAN 4 | AM_CXXFLAGS += -fsanitize=address -fsanitize-address-use-after-scope 5 | endif 6 | 7 | if WITH_UBSAN 8 | AM_CXXFLAGS += -fsanitize=undefined 9 | endif 10 | 11 | SAN_FLAGS = -fno-optimize-sibling-calls -fno-omit-frame-pointer 12 | if WITH_ASAN 13 | AM_CXXFLAGS += $(SAN_FLAGS) 14 | else 15 | if WITH_UBSAN 16 | AM_CXXFLAGS += $(SAN_FLAGS) 17 | endif 18 | endif 19 | 20 | bin_PROGRAMS = patchelf 21 | 22 | patchelf_SOURCES = patchelf.cc elf.h patchelf.h 23 | -------------------------------------------------------------------------------- /src/patchelf.h: -------------------------------------------------------------------------------- 1 | #include <map> 2 | #include <memory> 3 | #include <optional> 4 | #include <set> 5 | #include <stdexcept> 6 | #include <string> 7 | #include <vector> 8 | 9 | #include "elf.h" 10 | 11 | using FileContents = std::shared_ptr<std::vector<unsigned char>>; 12 | 13 | #define ElfFileParams class Elf_Ehdr, class Elf_Phdr, class Elf_Shdr, class Elf_Addr, class Elf_Off, class Elf_Dyn, class Elf_Sym, class Elf_Versym, class Elf_Verdef, class Elf_Verdaux, class Elf_Verneed, class Elf_Vernaux, class Elf_Rel, class Elf_Rela, unsigned ElfClass 14 | #define ElfFileParamNames Elf_Ehdr, Elf_Phdr, Elf_Shdr, Elf_Addr, Elf_Off, Elf_Dyn, Elf_Sym, Elf_Versym, Elf_Verdef, Elf_Verdaux, Elf_Verneed, Elf_Vernaux, Elf_Rel, Elf_Rela, ElfClass 15 | 16 | template<class T> 17 | struct span 18 | { 19 | explicit span(T* d = {}, size_t l = {}) : data(d), len(l) {} 20 | span(T* from, T* to) : data(from), len(to-from) { assert(from <= to); } 21 | T& operator[](std::size_t i) { checkRange(i); return data[i]; } 22 | T* begin() { return data; } 23 | T* end() { return data + len; } 24 | auto size() const { return len; } 25 | explicit operator bool() const { return size() > 0; } 26 | 27 | private: 28 | void checkRange(std::size_t i) { 29 | if (i >= size()) throw std::out_of_range("error: Span access out of range."); 30 | } 31 | 32 | T* data; 33 | size_t len; 34 | }; 35 | 36 | template<ElfFileParams> 37 | class ElfFile 38 | { 39 | public: 40 | 41 | const FileContents fileContents; 42 | 43 | private: 44 | 45 | std::vector<Elf_Phdr> phdrs; 46 | std::vector<Elf_Shdr> shdrs; 47 | 48 | bool littleEndian; 49 | 50 | bool changed = false; 51 | 52 | bool isExecutable = false; 53 | 54 | using SectionName = std::string; 55 | using ReplacedSections = std::map<SectionName, std::string>; 56 | 57 | ReplacedSections replacedSections; 58 | 59 | std::string sectionNames; /* content of the .shstrtab section */ 60 | 61 | /* Align on 4 or 8 bytes boundaries on 32- or 64-bit platforms 62 | respectively. */ 63 | static constexpr size_t sectionAlignment = sizeof(Elf_Off); 64 | 65 | std::vector<SectionName> sectionsByOldIndex; 66 | 67 | public: 68 | explicit ElfFile(FileContents fileContents); 69 | 70 | [[nodiscard]] bool isChanged() const noexcept 71 | { 72 | return changed; 73 | } 74 | 75 | private: 76 | 77 | struct CompPhdr 78 | { 79 | const ElfFile * elfFile; 80 | bool operator ()(const Elf_Phdr & x, const Elf_Phdr & y) const noexcept 81 | { 82 | // A PHDR comes before everything else. 83 | if (elfFile->rdi(y.p_type) == PT_PHDR) return false; 84 | if (elfFile->rdi(x.p_type) == PT_PHDR) return true; 85 | 86 | // Sort non-PHDRs by address. 87 | return elfFile->rdi(x.p_paddr) < elfFile->rdi(y.p_paddr); 88 | } 89 | }; 90 | 91 | void sortPhdrs(); 92 | 93 | struct CompShdr 94 | { 95 | const ElfFile * elfFile; 96 | bool operator ()(const Elf_Shdr & x, const Elf_Shdr & y) const noexcept 97 | { 98 | return elfFile->rdi(x.sh_offset) < elfFile->rdi(y.sh_offset); 99 | } 100 | }; 101 | 102 | [[nodiscard]] unsigned int getPageSize() const noexcept; 103 | 104 | void sortShdrs(); 105 | 106 | void shiftFile(unsigned int extraPages, size_t sizeOffset, size_t extraBytes); 107 | 108 | [[nodiscard]] std::string getSectionName(const Elf_Shdr & shdr) const; 109 | 110 | const Elf_Shdr & findSectionHeader(const SectionName & sectionName) const; 111 | 112 | [[nodiscard]] std::optional<std::reference_wrapper<const Elf_Shdr>> tryFindSectionHeader(const SectionName & sectionName) const; 113 | 114 | template<class T> span<T> getSectionSpan(const Elf_Shdr & shdr) const; 115 | template<class T> span<T> getSectionSpan(const SectionName & sectionName); 116 | template<class T> span<T> tryGetSectionSpan(const SectionName & sectionName); 117 | 118 | [[nodiscard]] unsigned int getSectionIndex(const SectionName & sectionName) const; 119 | 120 | std::string & replaceSection(const SectionName & sectionName, 121 | unsigned int size); 122 | 123 | [[nodiscard]] bool hasReplacedSection(const SectionName & sectionName) const; 124 | [[nodiscard]] bool canReplaceSection(const SectionName & sectionName) const; 125 | 126 | void writeReplacedSections(Elf_Off & curOff, 127 | Elf_Addr startAddr, Elf_Off startOffset); 128 | 129 | void rewriteHeaders(Elf_Addr phdrAddress); 130 | 131 | void rewriteSectionsLibrary(); 132 | 133 | void rewriteSectionsExecutable(); 134 | 135 | void normalizeNoteSegments(); 136 | 137 | public: 138 | 139 | void rewriteSections(bool force = false); 140 | 141 | [[nodiscard]] std::string getInterpreter() const; 142 | 143 | typedef enum { printOsAbi, replaceOsAbi } osAbiMode; 144 | 145 | void modifyOsAbi(osAbiMode op, const std::string & newOsAbi); 146 | 147 | typedef enum { printSoname, replaceSoname } sonameMode; 148 | 149 | void modifySoname(sonameMode op, const std::string & newSoname); 150 | 151 | void setInterpreter(const std::string & newInterpreter); 152 | 153 | typedef enum { rpPrint, rpShrink, rpSet, rpAdd, rpRemove } RPathOp; 154 | 155 | void modifyRPath(RPathOp op, const std::vector<std::string> & allowedRpathPrefixes, std::string newRPath); 156 | std::string shrinkRPath(char* rpath, std::vector<std::string> &neededLibs, const std::vector<std::string> & allowedRpathPrefixes); 157 | void removeRPath(Elf_Shdr & shdrDynamic); 158 | 159 | void addNeeded(const std::set<std::string> & libs); 160 | 161 | void removeNeeded(const std::set<std::string> & libs); 162 | 163 | void replaceNeeded(const std::map<std::string, std::string> & libs); 164 | 165 | void printNeededLibs() const; 166 | 167 | void noDefaultLib(); 168 | 169 | void addDebugTag(); 170 | 171 | void renameDynamicSymbols(const std::unordered_map<std::string_view, std::string>&); 172 | 173 | void clearSymbolVersions(const std::set<std::string> & syms); 174 | 175 | enum class ExecstackMode { print, set, clear }; 176 | 177 | void modifyExecstack(ExecstackMode op); 178 | 179 | private: 180 | struct GnuHashTable { 181 | using BloomWord = Elf_Addr; 182 | struct Header { 183 | uint32_t numBuckets, symndx, maskwords, shift2; 184 | } m_hdr; 185 | span<BloomWord> m_bloomFilters; 186 | span<uint32_t> m_buckets, m_table; 187 | }; 188 | GnuHashTable parseGnuHashTable(span<char> gh); 189 | 190 | struct HashTable { 191 | struct Header { 192 | uint32_t numBuckets, nchain; 193 | } m_hdr; 194 | span<uint32_t> m_buckets, m_chain; 195 | }; 196 | HashTable parseHashTable(span<char> gh); 197 | 198 | void rebuildGnuHashTable(span<char> strTab, span<Elf_Sym> dynsyms); 199 | void rebuildHashTable(span<char> strTab, span<Elf_Sym> dynsyms); 200 | 201 | using Elf_Rel_Info = decltype(Elf_Rel::r_info); 202 | 203 | uint32_t rel_getSymId(const Elf_Rel_Info& info) const 204 | { 205 | if constexpr (std::is_same_v<Elf_Rel, Elf64_Rel>) 206 | return ELF64_R_SYM(info); 207 | else 208 | return ELF32_R_SYM(info); 209 | } 210 | 211 | Elf_Rel_Info rel_setSymId(Elf_Rel_Info info, uint32_t id) const 212 | { 213 | if constexpr (std::is_same_v<Elf_Rel, Elf64_Rel>) 214 | { 215 | constexpr Elf_Rel_Info idmask = (~Elf_Rel_Info()) << 32; 216 | info = (info & ~idmask) | (Elf_Rel_Info(id) << 32); 217 | } 218 | else 219 | { 220 | constexpr Elf_Rel_Info idmask = (~Elf_Rel_Info()) << 8; 221 | info = (info & ~idmask) | (Elf_Rel_Info(id) << 8); 222 | } 223 | return info; 224 | } 225 | 226 | template<class ElfRelType, class RemapFn> 227 | void changeRelocTableSymIds(const Elf_Shdr& shdr, RemapFn&& old2newSymId) 228 | { 229 | static_assert(std::is_same_v<ElfRelType, Elf_Rel> || std::is_same_v<ElfRelType, Elf_Rela>); 230 | 231 | for (auto& r : getSectionSpan<ElfRelType>(shdr)) 232 | { 233 | auto info = rdi(r.r_info); 234 | auto oldSymIdx = rel_getSymId(info); 235 | auto newSymIdx = old2newSymId(oldSymIdx); 236 | if (newSymIdx != oldSymIdx) 237 | wri(r.r_info, rel_setSymId(info, newSymIdx)); 238 | } 239 | } 240 | 241 | template<class StrIdxCallback> 242 | void forAllStringReferences(const Elf_Shdr& strTabHdr, StrIdxCallback&& fn); 243 | 244 | template<class T, class U> 245 | auto follow(U* ptr, size_t offset) -> T* { 246 | return offset ? (T*)(((char*)ptr)+offset) : nullptr; 247 | }; 248 | 249 | template<class VdFn, class VaFn> 250 | void forAll_ElfVer(span<Elf_Verdef> vdspan, VdFn&& vdfn, VaFn&& vafn) 251 | { 252 | auto* vd = vdspan.begin(); 253 | for (; vd; vd = follow<Elf_Verdef>(vd, rdi(vd->vd_next))) 254 | { 255 | vdfn(*vd); 256 | auto va = follow<Elf_Verdaux>(vd, rdi(vd->vd_aux)); 257 | for (; va; va = follow<Elf_Verdaux>(va, rdi(va->vda_next))) 258 | vafn(*va); 259 | } 260 | } 261 | 262 | template<class VnFn, class VaFn> 263 | void forAll_ElfVer(span<Elf_Verneed> vnspan, VnFn&& vnfn, VaFn&& vafn) 264 | { 265 | auto* vn = vnspan.begin(); 266 | for (; vn; vn = follow<Elf_Verneed>(vn, rdi(vn->vn_next))) 267 | { 268 | vnfn(*vn); 269 | auto va = follow<Elf_Vernaux>(vn, rdi(vn->vn_aux)); 270 | for (; va; va = follow<Elf_Vernaux>(va, rdi(va->vna_next))) 271 | vafn(*va); 272 | } 273 | } 274 | 275 | /* Convert an integer in big or little endian representation (as 276 | specified by the ELF header) to this platform's integer 277 | representation. */ 278 | template<class I> 279 | constexpr I rdi(I i) const noexcept; 280 | 281 | /* Convert back to the ELF representation. */ 282 | template<class I, class U> 283 | constexpr inline I wri(I & t, U i) const 284 | { 285 | I val = static_cast<I>(i); 286 | if (static_cast<U>(val) != i) 287 | throw std::runtime_error { "value truncation" }; 288 | t = rdi(val); 289 | return val; 290 | } 291 | 292 | [[nodiscard]] Elf_Ehdr *hdr() noexcept { 293 | return reinterpret_cast<Elf_Ehdr *>(fileContents->data()); 294 | } 295 | 296 | [[nodiscard]] const Elf_Ehdr *hdr() const noexcept { 297 | return reinterpret_cast<const Elf_Ehdr *>(fileContents->data()); 298 | } 299 | }; 300 | -------------------------------------------------------------------------------- /tests/Makefile.am: -------------------------------------------------------------------------------- 1 | LIBS = 2 | 3 | check_PROGRAMS = simple-pie simple simple-execstack main too-many-strtab main-scoped big-dynstr no-rpath contiguous-note-sections 4 | 5 | no_rpath_arch_TESTS = \ 6 | no-rpath-alpha.sh \ 7 | no-rpath-amd64.sh \ 8 | no-rpath-armel.sh \ 9 | no-rpath-armhf.sh \ 10 | no-rpath-hurd-i386.sh \ 11 | no-rpath-i386.sh \ 12 | no-rpath-ia64.sh \ 13 | no-rpath-kfreebsd-amd64.sh \ 14 | no-rpath-kfreebsd-i386.sh \ 15 | no-rpath-mips.sh \ 16 | no-rpath-mipsel.sh \ 17 | no-rpath-powerpc.sh \ 18 | no-rpath-s390.sh \ 19 | no-rpath-sh4.sh \ 20 | no-rpath-sparc.sh 21 | 22 | src_TESTS = \ 23 | plain-fail.sh plain-run.sh shrink-rpath.sh set-interpreter-short.sh \ 24 | set-interpreter-long.sh set-rpath.sh add-rpath.sh no-rpath.sh big-dynstr.sh \ 25 | set-rpath-library.sh soname.sh shrink-rpath-with-allowed-prefixes.sh \ 26 | set-rpath-rel-map.sh \ 27 | force-rpath.sh \ 28 | plain-needed.sh \ 29 | output-flag.sh \ 30 | too-many-strtab.sh \ 31 | no-rpath-pie-powerpc.sh \ 32 | build-id.sh \ 33 | invalid-elf.sh \ 34 | endianness.sh \ 35 | contiguous-note-sections.sh \ 36 | no-gnu-hash.sh \ 37 | change-abi.sh \ 38 | grow-file.sh \ 39 | no-dynamic-section.sh \ 40 | args-from-file.sh \ 41 | basic-flags.sh \ 42 | set-empty-rpath.sh \ 43 | phdr-corruption.sh \ 44 | replace-needed.sh \ 45 | replace-add-needed.sh \ 46 | add-debug-tag.sh \ 47 | repeated-updates.sh \ 48 | empty-note.sh \ 49 | print-execstack.sh \ 50 | modify-execstack.sh \ 51 | rename-dynamic-symbols.sh \ 52 | overlapping-segments-after-rounding.sh \ 53 | shared-rpath.sh \ 54 | short-first-segment.sh \ 55 | empty-note.sh \ 56 | set-interpreter-same.sh 57 | 58 | build_TESTS = \ 59 | $(no_rpath_arch_TESTS) 60 | 61 | TESTS = $(src_TESTS) $(build_TESTS) 62 | 63 | EXTRA_DIST = no-rpath-prebuild $(src_TESTS) no-rpath-prebuild.sh invalid-elf endianness empty-note \ 64 | overlapping-segments-after-rounding short-first-segment.gz 65 | 66 | TESTS_ENVIRONMENT = PATCHELF_DEBUG=1 STRIP=$(STRIP) NM=$(NM) OBJDUMP=$(OBJDUMP) READELF=$(READELF) OBJCOPY=$(OBJCOPY) STRINGS=$(STRINGS) 67 | 68 | $(no_rpath_arch_TESTS): no-rpath-prebuild.sh 69 | @ln -s lt; $@ 70 | 71 | CLEANFILES = big-dynstr.c 72 | clean-local: 73 | $(RM) -r scratch $(no_rpath_arch_TESTS) 74 | 75 | # by default, use -fpic to compile 76 | AM_CFLAGS = -fpic 77 | LDFLAGS_local = -Wl,--disable-new-dtags -Wl,-rpath-link=. -L. $(AM_LDFLAGS) 78 | LDFLAGS_sharedlib = -Wl,--disable-new-dtags -shared -L. $(AM_LDFLAGS) 79 | export NIX_DONT_SET_RPATH=1 80 | export NIX_LDFLAGS= 81 | 82 | simple_SOURCES = simple.c 83 | # no -fpic for simple.o 84 | simple_CFLAGS = 85 | simple_LDFLAGS = -Wl,-z,noexecstack 86 | 87 | simple_pie_SOURCES = simple.c 88 | simple_pie_CFLAGS = -fPIC -pie 89 | 90 | simple_execstack_SOURCES = simple.c 91 | simple_execstack_CFLAGS = 92 | simple_execstack_LDFLAGS = -Wl,-z,execstack 93 | 94 | main_SOURCES = main.c 95 | main_LDADD = -lfoo $(AM_LDADD) 96 | main_DEPENDENCIES = libfoo.so 97 | main_LDFLAGS = $(LDFLAGS_local) 98 | 99 | main_scoped_SOURCES = main.c 100 | main_scoped_LDADD = -lfoo-scoped $(AM_LDADD) 101 | main_scoped_DEPENDENCIES = libfoo-scoped.so 102 | main_scoped_LDFLAGS = $(LDFLAGS_local) 103 | 104 | big-dynstr.c: main.c 105 | cat lt; > big-dynstr.c 106 | i=1; while [ $i -le 2000 ]; do echo "void f$i(void) { };"; i=$(($i + 1)); done >> big-dynstr.c 107 | 108 | nodist_big_dynstr_SOURCES = big-dynstr.c 109 | big_dynstr_LDADD = -lfoo $(AM_LDADD) 110 | big_dynstr_DEPENDENCIES = libfoo.so 111 | big_dynstr_LDFLAGS = $(LDFLAGS_local) 112 | 113 | # somehow bug does not trigger if we use 114 | # normal autotools rules to build the program: 115 | # https://github.com/NixOS/patchelf/pull/303 116 | libbig-dynstr.so: big-dynstr.c 117 | $(CC) -fPIC -shared -o $@ lt; 118 | libbig-dynstr.debug: libbig-dynstr.so 119 | $(STRIP) --only-keep-debug libbig-dynstr.so -o libbig-dynstr.debug 120 | check_DATA = libbig-dynstr.debug 121 | 122 | 123 | # declare local shared libraries as programs as: 124 | # - without libtool, only archives (static libraries) can be built by automake 125 | # - with libtool, it is difficult to control options 126 | # - with libtool, it is not possible to compile convenience *dynamic* libraries :-( 127 | check_PROGRAMS += libfoo.so libfoo-scoped.so libbar.so libbar-scoped.so libsimple.so libsimple-execstack.so libbuildid.so libtoomanystrtab.so \ 128 | phdr-corruption.so many-syms-main libmany-syms.so liboveralign.so libshared-rpath.so 129 | 130 | libbuildid_so_SOURCES = simple.c 131 | libbuildid_so_LDFLAGS = $(LDFLAGS_sharedlib) -Wl,--build-id 132 | 133 | libfoo_so_SOURCES = foo.c 134 | libfoo_so_LDADD = -lbar $(AM_LDADD) 135 | libfoo_so_DEPENDENCIES = libbar.so 136 | libfoo_so_LDFLAGS = $(LDFLAGS_sharedlib) 137 | 138 | libfoo_scoped_so_SOURCES = foo.c 139 | libfoo_scoped_so_LDADD = -lbar-scoped $(AM_LDADD) 140 | libfoo_scoped_so_DEPENDENCIES = libbar-scoped.so 141 | libfoo_scoped_so_LDFLAGS = $(LDFLAGS_sharedlib) 142 | 143 | libbar_so_SOURCES = bar.c 144 | libbar_so_LDFLAGS = $(LDFLAGS_sharedlib) -Wl,-rpath,`pwd`/no-such-path 145 | 146 | libbar_scoped_so_SOURCES = bar.c 147 | libbar_scoped_so_LDFLAGS = $(LDFLAGS_sharedlib) 148 | 149 | libsimple_so_SOURCES = simple.c 150 | libsimple_so_LDFLAGS = $(LDFLAGS_sharedlib) -Wl,-z,noexecstack 151 | 152 | liboveralign_so_SOURCES = simple.c 153 | liboveralign_so_LDFLAGS = $(LDFLAGS_sharedlib) -Wl,-z,max-page-size=0x10000 154 | 155 | libshared_rpath_so_SOURCES = shared-rpath.c 156 | libshared_rpath_so_LDFLAGS = $(LDFLAGS_sharedlib) -Wl,-rpath=a_symbol_name 157 | 158 | libsimple_execstack_so_SOURCES = simple.c 159 | libsimple_execstack_so_LDFLAGS = $(LDFLAGS_sharedlib) -Wl,-z,execstack 160 | 161 | too_many_strtab_SOURCES = too-many-strtab.c too-many-strtab2.s 162 | libtoomanystrtab_so_SOURCES = too-many-strtab.c too-many-strtab2.s 163 | libtoomanystrtab_so_LDFLAGS = $(LDFLAGS_sharedlib) 164 | 165 | many_syms_main_SOURCES = many-syms-main.c 166 | many_syms_main_LDFLAGS = $(LDFLAGS_local) 167 | many_syms_main_LDADD = -lmany-syms $(AM_LDADD) 168 | many_syms_main_DEPENDENCIES = libmany-syms.so 169 | many_syms_main_CFLAGS = -pie -fPIE 170 | libmany_syms_so_SOURCES = many-syms.c 171 | libmany_syms_so_LDFLAGS = $(LDFLAGS_sharedlib) 172 | 173 | no_rpath_SOURCES = no-rpath.c 174 | # no -fpic for no-rpath.o 175 | no_rpath_CFLAGS = 176 | no_rpath_LDFLAGS = 177 | 178 | contiguous_note_sections_SOURCES = contiguous-note-sections.s contiguous-note-sections.ld 179 | contiguous_note_sections_LDFLAGS = -nostdlib -T $(srcdir)/contiguous-note-sections.ld 180 | contiguous_note_sections_CFLAGS = -pie 181 | 182 | phdr_corruption_so_SOURCES = void.c phdr-corruption.ld 183 | phdr_corruption_so_LDFLAGS = -nostdlib -shared -Wl,-T$(srcdir)/phdr-corruption.ld 184 | phdr_corruption_so_CFLAGS = 185 | 186 | many-syms.c: 187 | i=1; while [ $i -le 2000 ]; do echo "void f$i() {};"; i=$(($i + 1)); done > $@ 188 | 189 | many-syms-main.c: 190 | echo "int main() {" > $@ 191 | i=1; while [ $i -le 2000 ]; do echo "void f$i(); f$i();"; i=$(($i + 1)); done >> $@ 192 | echo "}" >> $@ 193 | 194 | -------------------------------------------------------------------------------- /tests/add-debug-tag.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | READELF=${READELF:-readelf} 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | cp libsimple.so "${SCRATCH}"/ 9 | 10 | # check there is no DT_DEBUG tag 11 | debugTag=$($READELF -d "${SCRATCH}/libsimple.so") 12 | echo ".dynamic before: $debugTag" 13 | if echo "$debugTag" | grep -q DEBUG; then 14 | echo "failed --add-debug-tag test. Expected no line with (DEBUG), got: $debugTag" 15 | exit 1 16 | fi 17 | 18 | # set DT_DEBUG 19 | ../src/patchelf --add-debug-tag "${SCRATCH}/libsimple.so" 20 | 21 | # check there is DT_DEBUG tag 22 | debugTag=$($READELF -d "${SCRATCH}/libsimple.so") 23 | echo ".dynamic before: $debugTag" 24 | if ! echo "$debugTag" | grep -q DEBUG; then 25 | echo "failed --add-debug-tag test. Expected line with (DEBUG), got: $debugTag" 26 | exit 1 27 | fi 28 | -------------------------------------------------------------------------------- /tests/add-rpath.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | mkdir -p "${SCRATCH}/libsA" 7 | mkdir -p "${SCRATCH}/libsB" 8 | 9 | cp main "${SCRATCH}"/ 10 | cp libfoo.so "${SCRATCH}/libsA/" 11 | cp libbar.so "${SCRATCH}/libsB/" 12 | 13 | ../src/patchelf --force-rpath --add-rpath "$(pwd)/${SCRATCH}/libsA" "${SCRATCH}/main" 14 | ../src/patchelf --force-rpath --add-rpath "$(pwd)/${SCRATCH}/libsB" "${SCRATCH}/main" 15 | 16 | if test "$(uname)" = FreeBSD; then 17 | LD_LIBRARY_PATH="$(pwd)/${SCRATCH}/libsB" 18 | export LD_LIBRARY_PATH 19 | fi 20 | 21 | exitCode=0 22 | (cd "${SCRATCH}" && ./main) || exitCode=$? 23 | 24 | if test "$exitCode" != 46; then 25 | echo "bad exit code!" 26 | exit 1 27 | fi 28 | -------------------------------------------------------------------------------- /tests/args-from-file.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | 7 | cp main "${SCRATCH}"/ 8 | SOME_PATH=$(pwd)/${SCRATCH}/some-path 9 | printf "%s" "$SOME_PATH" >> "${SCRATCH}"/add-rpath 10 | 11 | ../src/patchelf --print-rpath "${SCRATCH}"/main | grep "$SOME_PATH" && exit 1 12 | ../src/patchelf --add-rpath @"${SCRATCH}"/add-rpath "${SCRATCH}"/main 13 | ../src/patchelf --print-rpath "${SCRATCH}"/main | grep "$SOME_PATH" 14 | 15 | # should print error message and fail 16 | ../src/patchelf --set-rpath @"${SCRATCH}"/does-not-exist "${SCRATCH}"/main 2>&1 | grep "getting info about" 17 | -------------------------------------------------------------------------------- /tests/bar.c: -------------------------------------------------------------------------------- 1 | #include <stdio.h> 2 | 3 | int bar() 4 | { 5 | printf("This is bar()!\n"); 6 | return 34; 7 | } 8 | -------------------------------------------------------------------------------- /tests/basic-flags.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | set -x 4 | ../src/patchelf --version | grep -q patchelf 5 | ../src/patchelf --help 2>&1 | grep -q patchelf 6 | ../src/patchelf 2>&1 | grep -q patchelf 7 | -------------------------------------------------------------------------------- /tests/big-dynstr.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | mkdir -p "${SCRATCH}/libsA" 7 | mkdir -p "${SCRATCH}/libsB" 8 | 9 | cp big-dynstr "${SCRATCH}/" 10 | cp libfoo.so "${SCRATCH}/libsA/" 11 | cp libbar.so "${SCRATCH}/libsB/" 12 | 13 | oldRPath=$(../src/patchelf --print-rpath "${SCRATCH}/big-dynstr") 14 | if test -z "$oldRPath"; then oldRPath="/oops"; fi 15 | ../src/patchelf --force-rpath --set-rpath "$oldRPath:$(pwd)/${SCRATCH}/libsA:$(pwd)/${SCRATCH}/libsB" "${SCRATCH}/big-dynstr" 16 | 17 | if test "$(uname)" = FreeBSD; then 18 | LD_LIBRARY_PATH="$(pwd)/${SCRATCH}/libsB" 19 | export LD_LIBRARY_PATH 20 | fi 21 | 22 | exitCode=0 23 | cd "${SCRATCH}" && ./big-dynstr || exitCode=$? 24 | 25 | if test "$exitCode" != 46; then 26 | echo "bad exit code!" 27 | exit 1 28 | fi 29 | -------------------------------------------------------------------------------- /tests/build-id.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | READELF=${READELF:-readelf} 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | cp libbuildid.so "${SCRATCH}/" 9 | 10 | long_rpath="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" 11 | 12 | ../src/patchelf \ 13 | --set-rpath "$long_rpath" "${SCRATCH}/libbuildid.so" 14 | 15 | # older readelf versions do not recognize build id, but we can grep by constant 16 | LANG=en_US 17 | ${READELF} -n "${SCRATCH}/libbuildid.so" | grep -q -F -e 'Build ID' -e 'Unknown note type: (0x00000003)' 18 | -------------------------------------------------------------------------------- /tests/change-abi.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | SCRATCH=scratch/$(basename "$0" .sh) 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | cp simple-pie "${SCRATCH}/simple-pie" 9 | 10 | # Save the old OS ABI 11 | OLDABI=$(../src/patchelf --print-os-abi "${SCRATCH}/simple-pie") 12 | # Ensure it's not empty 13 | test -n "$OLDABI" 14 | 15 | # Change OS ABI and verify it has been changed 16 | for ABI in "System V" "HP-UX" "NetBSD" "Linux" "GNU Hurd" "Solaris" "AIX" "IRIX" "FreeBSD" "Tru64" "OpenBSD" "OpenVMS"; do 17 | echo "Set OS ABI to '$ABI'..." 18 | ../src/patchelf --set-os-abi "$ABI" "${SCRATCH}/simple-pie" 19 | 20 | echo "Check is OS ABI is '$ABI'..." 21 | NEWABI=$(../src/patchelf --print-os-abi "${SCRATCH}/simple-pie") 22 | test "$NEWABI" = "$ABI" 23 | done 24 | 25 | # Reset OS ABI to the saved one 26 | ../src/patchelf --set-os-abi "$OLDABI" "${SCRATCH}/simple-pie" 27 | 28 | # Verify we still can run the executable 29 | "${SCRATCH}/simple-pie" 30 | -------------------------------------------------------------------------------- /tests/contiguous-note-sections.ld: -------------------------------------------------------------------------------- 1 | PHDRS 2 | { 3 | headers PT_PHDR PHDRS ; 4 | notes PT_NOTE; 5 | text PT_LOAD FILEHDR PHDRS ; 6 | data PT_LOAD ; 7 | interp PT_INTERP ; 8 | dynamic PT_DYNAMIC ; 9 | } 10 | 11 | SECTIONS 12 | { 13 | . = SIZEOF_HEADERS; 14 | . = ALIGN(4); 15 | 16 | .note.my-section0 : { *(.note.my-section0) } :notes :text 17 | .note.my-section1 : { *(.note.my-section1) } :notes :text 18 | 19 | .interp : { *(.interp) } :text :interp 20 | .text : { *(.text) } :text 21 | .rodata : { *(.rodata) } /* defaults to :text */ 22 | 23 | .data : { *(.data) } :data 24 | } 25 | -------------------------------------------------------------------------------- /tests/contiguous-note-sections.s: -------------------------------------------------------------------------------- 1 | /* 2 | * Testcase for error: 3 | * patchelf: cannot normalize PT_NOTE segment: non-contiguous SHT_NOTE sections 4 | */ 5 | .section ".note.my-section0", "a", %note 6 | .align 4 7 | .long 1f - 0f /* name length (not including padding) */ 8 | .long 3f - 2f /* desc length (not including padding) */ 9 | .long 1 /* type = NT_VERSION */ 10 | 0: .asciz "my-version-12345" /* name */ 11 | 1: .align 4 12 | 2: .long 1 /* desc - toolchain version number, 32-bit LE */ 13 | 3: .align 4 14 | 15 | .section ".note.my-section1", "a", %note 16 | .align 8 17 | .long 1f - 0f /* name length (not including padding) */ 18 | .long 3f - 2f /* desc length (not including padding) */ 19 | .long 1 /* type = NT_VERSION */ 20 | 0: .asciz "my-version-1" /* name */ 21 | 1: .align 4 22 | 2: .long 1 /* desc - toolchain version number, 32-bit LE */ 23 | 3: .align 4 24 | -------------------------------------------------------------------------------- /tests/contiguous-note-sections.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | SCRATCH=scratch/$(basename "$0" .sh) 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | cp contiguous-note-sections "${SCRATCH}/" 9 | 10 | # Running --set-interpreter on this binary should not produce the following 11 | # error: 12 | # patchelf: cannot normalize PT_NOTE segment: non-contiguous SHT_NOTE sections 13 | ../src/patchelf --set-interpreter ld-linux-x86-64.so.2 "${SCRATCH}/contiguous-note-sections" 14 | -------------------------------------------------------------------------------- /tests/empty-note: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/empty-note -------------------------------------------------------------------------------- /tests/empty-note.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | SCRATCH=scratch/$(basename "$0" .sh) 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | cp "$(dirname "$(readlink -f "$0")")/empty-note" "${SCRATCH}/" 8 | 9 | # Running --set-interpreter on this binary should not produce the following 10 | # error: 11 | # patchelf: cannot normalize PT_NOTE segment: non-contiguous SHT_NOTE sections 12 | ../src/patchelf --set-interpreter ld-linux-x86-64.so.2 "${SCRATCH}/empty-note" 13 | -------------------------------------------------------------------------------- /tests/endianness.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | PATCHELF="../src/patchelf" 4 | 5 | for arch in ppc64 ppc64le; do 6 | rm -rf "${SCRATCH}" 7 | mkdir -p "${SCRATCH}" 8 | 9 | cp "${srcdir:?}/endianness/${arch}/main" "${srcdir}/endianness/${arch}/libtest.so" "${SCRATCH}/" 10 | 11 | rpath="${PWD}/${SCRATCH}" 12 | 13 | # set rpath to scratch dir 14 | ${PATCHELF} --output "${SCRATCH}/main-rpath" --set-rpath "$rpath" "${SCRATCH}/main" 15 | 16 | # attempt to shrink rpath, should not result in empty rpath 17 | ${PATCHELF} --output "${SCRATCH}/main-shrunk" --shrink-rpath --debug "${SCRATCH}/main-rpath" 18 | 19 | # check whether rpath is still present 20 | if ! ${PATCHELF} --print-rpath "${SCRATCH}/main-shrunk" | grep -q "$rpath"; then 21 | echo "rpath was removed for ${arch}" 22 | exit 1 23 | fi 24 | done 25 | -------------------------------------------------------------------------------- /tests/endianness/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | $(CC) -xc -nostdlib -shared -o libtest.so - <<< 'void test() {}' 3 | $(CC) -xc -nostdlib -L. -ltest -o main - <<< 'void _start() {}' 4 | -------------------------------------------------------------------------------- /tests/endianness/ppc64/libtest.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/endianness/ppc64/libtest.so -------------------------------------------------------------------------------- /tests/endianness/ppc64/main: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/endianness/ppc64/main -------------------------------------------------------------------------------- /tests/endianness/ppc64le/libtest.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/endianness/ppc64le/libtest.so -------------------------------------------------------------------------------- /tests/endianness/ppc64le/main: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/endianness/ppc64le/main -------------------------------------------------------------------------------- /tests/foo.c: -------------------------------------------------------------------------------- 1 | #include <stdio.h> 2 | 3 | /* Include a bogus .interp section in libfoo.so (NIXPKGS-98). 4 | Borrowed from Glibc. */ 5 | const char __invoke_dynamic_linker__[] __attribute__ ((section (".interp"))) = "/foo/bar"; 6 | 7 | int bar(); 8 | 9 | int foo() 10 | { 11 | printf("This is foo()!\n"); 12 | return 12 + bar(); 13 | } 14 | -------------------------------------------------------------------------------- /tests/force-rpath.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | OBJDUMP=${OBJDUMP:-objdump} 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | SCRATCHFILE=${SCRATCH}/libfoo.so 9 | cp libfoo.so "$SCRATCHFILE" 10 | 11 | doit() { 12 | set +x 13 | ../src/patchelf "$@" "$SCRATCHFILE" 14 | set -x 15 | } 16 | 17 | expect() { 18 | out=$("$OBJDUMP" -x "$SCRATCHFILE" | grep PATH || true) 19 | 20 | for i in $out; do 21 | if [ "$i" != "$1" ]; then 22 | echo "Expected '$*' but got '$out'" 23 | exit 1 24 | fi 25 | shift 26 | done 27 | } 28 | 29 | doit --remove-rpath 30 | expect "" 31 | doit --set-rpath foo 32 | expect RUNPATH foo 33 | doit --force-rpath --set-rpath foo 34 | expect RPATH foo 35 | doit --force-rpath --set-rpath bar 36 | expect RPATH bar 37 | doit --remove-rpath 38 | expect 39 | doit --force-rpath --set-rpath foo 40 | expect RPATH foo 41 | doit --set-rpath foo 42 | expect RUNPATH foo 43 | doit --set-rpath bar 44 | expect RUNPATH bar 45 | -------------------------------------------------------------------------------- /tests/grow-file.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | SCRATCH=scratch/$(basename "$0" .sh) 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | cp simple-pie "${SCRATCH}/simple-pie" 9 | 10 | # Add a large rpath 11 | printf '=%.0s' $(seq 1 4096) > "${SCRATCH}/foo.bin" 12 | 13 | # Grow the file 14 | ../src/patchelf --add-rpath @"${SCRATCH}/foo.bin" "${SCRATCH}/simple-pie" 15 | 16 | # Make sure we can still run it 17 | "${SCRATCH}/simple-pie" 18 | -------------------------------------------------------------------------------- /tests/invalid-elf.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -u 2 | 3 | # Usage: killed_by_signal $? 4 | # 5 | # Returns true if the exit code indicates that the program was killed 6 | # by a signal. This works because the exit code of processes that were 7 | # killed by a signal is 128 plus the signal number. 8 | killed_by_signal() { 9 | [ "$1" -ge 128 ] 10 | } 11 | 12 | 13 | # The directory containing all our input files. 14 | TEST_DIR=$(dirname "$(readlink -f "$0")")/invalid-elf 15 | 16 | # Each test case is listed here. The names should roughly indicate 17 | # what makes the given ELF file invalid. 18 | TEST_CASES="invalid-shrstrtab-idx invalid-shrstrtab-size invalid-shrstrtab-zero 19 | invalid-shrstrtab-nonterm invalid-shdr-name invalid-phdr-offset" 20 | 21 | FAILED_TESTS="" 22 | 23 | for tcase in $TEST_CASES; do 24 | if [ ! -r "$TEST_DIR/$tcase" ]; then 25 | echo "Cannot read test case: $tcase" 26 | exit 1 27 | fi 28 | 29 | ../src/patchelf --output /dev/null "$TEST_DIR/$tcase" 30 | if killed_by_signal $?; then 31 | FAILED_TESTS="$FAILED_TESTS $tcase" 32 | fi 33 | done 34 | 35 | if [ -z "$FAILED_TESTS" ]; then 36 | exit 0 37 | else 38 | echo "Failed tests: $FAILED_TESTS" 39 | exit 1 40 | fi 41 | -------------------------------------------------------------------------------- /tests/invalid-elf/invalid-phdr-offset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/invalid-elf/invalid-phdr-offset -------------------------------------------------------------------------------- /tests/invalid-elf/invalid-shdr-name: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/invalid-elf/invalid-shdr-name -------------------------------------------------------------------------------- /tests/invalid-elf/invalid-shrstrtab-nonterm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/invalid-elf/invalid-shrstrtab-nonterm -------------------------------------------------------------------------------- /tests/invalid-elf/invalid-shrstrtab-zero: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/invalid-elf/invalid-shrstrtab-zero -------------------------------------------------------------------------------- /tests/main.c: -------------------------------------------------------------------------------- 1 | #include <stdio.h> 2 | 3 | char buf[16 * 1024 * 1024]; 4 | 5 | int foo(); 6 | 7 | int main(int argc, char * * argv) 8 | { 9 | int x; 10 | printf("Hello World\n"); 11 | x = foo(); 12 | printf("Result is %d\n", x); 13 | return x; 14 | } 15 | -------------------------------------------------------------------------------- /tests/modify-execstack.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | PATCHELF=$(readlink -f "../src/patchelf") 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | cp simple "${SCRATCH}"/ 9 | cp simple-execstack "${SCRATCH}"/ 10 | cp libsimple.so "${SCRATCH}"/ 11 | cp libsimple-execstack.so "${SCRATCH}"/ 12 | 13 | cd "${SCRATCH}" 14 | 15 | 16 | ## simple 17 | 18 | cp simple backup 19 | 20 | if ! ${PATCHELF} --print-execstack simple | grep -q 'execstack: -'; then 21 | echo "[simple] wrong initial execstack detection" 22 | ${PATCHELF} --print-execstack simple 23 | exit 1 24 | fi 25 | 26 | if ! ${PATCHELF} --clear-execstack simple; then 27 | echo "[simple] failed noop initial clear" 28 | exit 1 29 | fi 30 | 31 | if ! ${PATCHELF} --set-execstack simple; then 32 | echo "[simple] failed set" 33 | exit 1 34 | fi 35 | 36 | if ! ${PATCHELF} --print-execstack simple | grep -q 'execstack: X'; then 37 | echo "[simple] wrong execstack detection after set" 38 | ${PATCHELF} --print-execstack simple 39 | exit 1 40 | fi 41 | 42 | if diff simple backup; then 43 | echo "[simple] no change after set" 44 | exit 1 45 | fi 46 | 47 | if ! ${PATCHELF} --set-execstack simple; then 48 | echo "[simple] failed noop set" 49 | exit 1 50 | fi 51 | 52 | if ! ${PATCHELF} --clear-execstack simple; then 53 | echo "[simple] failed clear after set" 54 | exit 1 55 | fi 56 | 57 | if ! ${PATCHELF} --print-execstack simple | grep -q 'execstack: -'; then 58 | echo "[simple] wrong execstack detection after clear after set" 59 | ${PATCHELF} --print-execstack simple 60 | exit 1 61 | fi 62 | 63 | if ! diff simple backup; then 64 | echo "[simple] change against backup after clear after set" 65 | exit 1 66 | fi 67 | 68 | 69 | ## simple-execstack 70 | 71 | cp simple-execstack backup 72 | 73 | if ! ${PATCHELF} --print-execstack simple-execstack | grep -q 'execstack: X'; then 74 | echo "[simple-execstack] wrong initial execstack detection" 75 | ${PATCHELF} --print-execstack simple-execstack 76 | exit 1 77 | fi 78 | 79 | if ! ${PATCHELF} --set-execstack simple-execstack; then 80 | echo "[simple-execstack] failed noop initial set" 81 | exit 1 82 | fi 83 | 84 | if ! ${PATCHELF} --clear-execstack simple-execstack; then 85 | echo "[simple-execstack] failed clear" 86 | exit 1 87 | fi 88 | 89 | if ! ${PATCHELF} --print-execstack simple-execstack | grep -q 'execstack: -'; then 90 | echo "[simple-execstack] wrong execstack detection after clear" 91 | ${PATCHELF} --print-execstack simple-execstack 92 | exit 1 93 | fi 94 | 95 | if diff simple-execstack backup; then 96 | echo "[simple-execstack] no change after set" 97 | exit 1 98 | fi 99 | 100 | if ! ${PATCHELF} --clear-execstack simple-execstack; then 101 | echo "[simple-execstack] failed noop clear" 102 | exit 1 103 | fi 104 | 105 | if ! ${PATCHELF} --set-execstack simple-execstack; then 106 | echo "[simple-execstack] failed set after clear" 107 | exit 1 108 | fi 109 | 110 | if ! ${PATCHELF} --print-execstack simple-execstack | grep -q 'execstack: X'; then 111 | echo "[simple-execstack] wrong execstack detection after set after clear" 112 | ${PATCHELF} --print-execstack simple-execstack 113 | exit 1 114 | fi 115 | 116 | if ! diff simple-execstack backup; then 117 | echo "[simple-execstack] change against backup after set after clear" 118 | exit 1 119 | fi 120 | 121 | 122 | ## libsimple.so 123 | 124 | cp libsimple.so backup 125 | 126 | if ! ${PATCHELF} --print-execstack libsimple.so | grep -q 'execstack: -'; then 127 | echo "[libsimple.so] wrong initial execstack detection" 128 | ${PATCHELF} --print-execstack libsimple.so 129 | exit 1 130 | fi 131 | 132 | if ! ${PATCHELF} --clear-execstack libsimple.so; then 133 | echo "[libsimple.so] failed noop initial clear" 134 | exit 1 135 | fi 136 | 137 | if ! ${PATCHELF} --set-execstack libsimple.so; then 138 | echo "[libsimple.so] failed set" 139 | exit 1 140 | fi 141 | 142 | if ! ${PATCHELF} --print-execstack libsimple.so | grep -q 'execstack: X'; then 143 | echo "[libsimple.so] wrong execstack detection after set" 144 | ${PATCHELF} --print-execstack libsimple.so 145 | exit 1 146 | fi 147 | 148 | if diff libsimple.so backup; then 149 | echo "[libsimple.so] no change after set" 150 | exit 1 151 | fi 152 | 153 | if ! ${PATCHELF} --set-execstack libsimple.so; then 154 | echo "[libsimple.so] failed noop set" 155 | exit 1 156 | fi 157 | 158 | if ! ${PATCHELF} --clear-execstack libsimple.so; then 159 | echo "[libsimple.so] failed clear after set" 160 | exit 1 161 | fi 162 | 163 | if ! ${PATCHELF} --print-execstack libsimple.so | grep -q 'execstack: -'; then 164 | echo "[libsimple.so] wrong execstack detection after clear after set" 165 | ${PATCHELF} --print-execstack libsimple.so 166 | exit 1 167 | fi 168 | 169 | if ! diff libsimple.so backup; then 170 | echo "[libsimple.so] change against backup after clear after set" 171 | exit 1 172 | fi 173 | 174 | 175 | ## libsimple-execstack.so 176 | 177 | cp libsimple-execstack.so backup 178 | 179 | if ! ${PATCHELF} --print-execstack libsimple-execstack.so | grep -q 'execstack: X'; then 180 | echo "[libsimple-execstack.so] wrong initial execstack detection" 181 | ${PATCHELF} --print-execstack libsimple-execstack.so 182 | exit 1 183 | fi 184 | 185 | if ! ${PATCHELF} --set-execstack libsimple-execstack.so; then 186 | echo "[libsimple-execstack.so] failed noop initial set" 187 | exit 1 188 | fi 189 | 190 | if ! ${PATCHELF} --clear-execstack libsimple-execstack.so; then 191 | echo "[libsimple-execstack.so] failed clear" 192 | exit 1 193 | fi 194 | 195 | if ! ${PATCHELF} --print-execstack libsimple-execstack.so | grep -q 'execstack: -'; then 196 | echo "[libsimple-execstack.so] wrong execstack detection after clear" 197 | ${PATCHELF} --print-execstack libsimple-execstack.so 198 | exit 1 199 | fi 200 | 201 | if diff libsimple-execstack.so backup; then 202 | echo "[libsimple-execstack.so] no change after set" 203 | exit 1 204 | fi 205 | 206 | if ! ${PATCHELF} --clear-execstack libsimple-execstack.so; then 207 | echo "[libsimple-execstack.so] failed noop clear" 208 | exit 1 209 | fi 210 | 211 | if ! ${PATCHELF} --set-execstack libsimple-execstack.so; then 212 | echo "[libsimple-execstack.so] failed set after clear" 213 | exit 1 214 | fi 215 | 216 | if ! ${PATCHELF} --print-execstack libsimple-execstack.so | grep -q 'execstack: X'; then 217 | echo "[libsimple-execstack.so] wrong execstack detection after set after clear" 218 | ${PATCHELF} --print-execstack libsimple-execstack.so 219 | exit 1 220 | fi 221 | 222 | if ! diff libsimple-execstack.so backup; then 223 | echo "[libsimple-execstack.so] change against backup after set after clear" 224 | exit 1 225 | fi 226 | -------------------------------------------------------------------------------- /tests/no-dynamic-section.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | # print rpath on library with stripped dynamic section 4 | ../src/patchelf --print-rpath libbig-dynstr.debug 5 | -------------------------------------------------------------------------------- /tests/no-gnu-hash.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | STRIP=${STRIP:-strip} 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | cp simple "${SCRATCH}/" 9 | 10 | ${STRIP} --remove-section=.gnu.hash "${SCRATCH}/simple" 11 | 12 | # Check if patchelf handles binaries with GNU_HASH in dynamic section but 13 | # without .gnu.hash section 14 | ../src/patchelf --set-interpreter /oops "${SCRATCH}/simple" 15 | -------------------------------------------------------------------------------- /tests/no-rpath-pie-powerpc.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | set -x 3 | SCRATCH=scratch/no-rpath-pie-powerpc 4 | READELF=${READELF:-readelf} 5 | 6 | no_rpath_bin="${srcdir:?}/no-rpath-prebuild/no-rpath-pie-powerpc" 7 | 8 | if [ ! -f "$no_rpath_bin" ]; then 9 | echo "no 'no-rpath' binary for '$ARCH' in '${srcdir:?}/no-rpath-prebuild'" 10 | exit 1 11 | fi 12 | 13 | rm -rf ${SCRATCH} 14 | mkdir -p ${SCRATCH} 15 | 16 | cp "$no_rpath_bin" ${SCRATCH}/no-rpath 17 | 18 | oldRPath=$(../src/patchelf --print-rpath ${SCRATCH}/no-rpath) 19 | if test -n "$oldRPath"; then exit 1; fi 20 | ../src/patchelf \ 21 | --set-interpreter "$(../src/patchelf --print-interpreter ../src/patchelf)" \ 22 | --set-rpath /foo:/bar:/xxxxxxxxxxxxxxx ${SCRATCH}/no-rpath 23 | 24 | newRPath=$(../src/patchelf --print-rpath ${SCRATCH}/no-rpath) 25 | if ! echo "$newRPath" | grep -q '/foo:/bar'; then 26 | echo "incomplete RPATH" 27 | exit 1 28 | fi 29 | 30 | # Tests for powerpc PIE endianness regressions 31 | readelfData=$(${READELF} -l ${SCRATCH}/no-rpath 2>&1) 32 | 33 | if [ "$(echo "$readelfData" | grep -c "PHDR")" != 1 ]; then 34 | # Triggered if PHDR errors appear on stderr 35 | echo "Unexpected number of occurences of PHDR in readelf results" 36 | exit 1 37 | fi 38 | 39 | virtAddr=$(echo "$readelfData" | grep "PHDR" | awk '{print $3}') 40 | if [ "$virtAddr" != "0x00000034" ]; then 41 | # Triggered if the virtual address is the incorrect endianness 42 | echo "Unexpected virt addr, expected [0x00000034] got [$virtAddr]" 43 | exit 1 44 | fi 45 | 46 | echo "$readelfData" | grep "LOAD" | while read -r line ; do 47 | align=$(echo "$line" | awk '{print $NF}') 48 | if [ "$align" != "0x10000" ]; then 49 | # Triggered if the target arch was not detected properly 50 | echo "Unexpected Align for LOAD segment, expected [0x10000] got [$align]" 51 | echo "Load segment: [$line]" 52 | exit 1 53 | fi 54 | done 55 | 56 | -------------------------------------------------------------------------------- /tests/no-rpath-prebuild.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | set -x 3 | ARCH="$1" 4 | PAGESIZE=4096 5 | 6 | if [ -z "$ARCH" ]; then 7 | ARCH=$(basename "$0" .sh | sed -e 's/^no-rpath-//') 8 | fi 9 | 10 | SCRATCH=scratch/no-rpath-$ARCH 11 | 12 | if [ -z "$ARCH" ] || [ "$ARCH" = prebuild ] ; then 13 | echo "Architecture required" 14 | exit 1 15 | fi 16 | 17 | no_rpath_bin="${srcdir:?}/no-rpath-prebuild/no-rpath-$ARCH" 18 | 19 | if [ ! -f "$no_rpath_bin" ]; then 20 | echo "no 'no-rpath' binary for '$ARCH' in '${srcdir:?}/no-rpath-prebuild'" 21 | exit 1 22 | fi 23 | 24 | rm -rf "${SCRATCH}" 25 | mkdir -p "${SCRATCH}" 26 | 27 | cp "$no_rpath_bin" "${SCRATCH}"/no-rpath 28 | 29 | oldRPath=$(../src/patchelf --page-size "${PAGESIZE}" --print-rpath "${SCRATCH}/no-rpath") 30 | if test -n "$oldRPath"; then exit 1; fi 31 | ../src/patchelf --page-size "${PAGESIZE}" \ 32 | --set-interpreter "$(../src/patchelf --page-size "${PAGESIZE}" --print-interpreter ../src/patchelf)" \ 33 | --set-rpath /foo:/bar:/xxxxxxxxxxxxxxx "${SCRATCH}"/no-rpath 34 | 35 | newRPath=$(../src/patchelf --page-size "${PAGESIZE}" --print-rpath "${SCRATCH}/no-rpath") 36 | if ! echo "$newRPath" | grep -q '/foo:/bar'; then 37 | echo "incomplete RPATH" 38 | exit 1 39 | fi 40 | -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-alpha: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-alpha -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-amd64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-amd64 -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-armel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-armel -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-armhf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-armhf -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-hurd-i386: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-hurd-i386 -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-i386: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-i386 -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-ia64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-ia64 -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-kfreebsd-amd64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-kfreebsd-amd64 -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-kfreebsd-i386: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-kfreebsd-i386 -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-mips: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-mips -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-mipsel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-mipsel -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-pie-powerpc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-pie-powerpc -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-powerpc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-powerpc -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-s390: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-s390 -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-sh4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-sh4 -------------------------------------------------------------------------------- /tests/no-rpath-prebuild/no-rpath-sparc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/no-rpath-prebuild/no-rpath-sparc -------------------------------------------------------------------------------- /tests/no-rpath.c: -------------------------------------------------------------------------------- 1 | #include <stdio.h> 2 | 3 | int main() { 4 | printf("Hello world\n"); 5 | return 0; 6 | } 7 | -------------------------------------------------------------------------------- /tests/no-rpath.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | 7 | cp no-rpath "${SCRATCH}/" 8 | 9 | oldRPath=$(../src/patchelf --print-rpath "${SCRATCH}/no-rpath") 10 | if test -n "$oldRPath"; then exit 1; fi 11 | ../src/patchelf \ 12 | --set-interpreter "$(../src/patchelf --print-interpreter ../src/patchelf)" \ 13 | --set-rpath /foo:/bar:/xxxxxxxxxxxxxxx "${SCRATCH}/no-rpath" 14 | 15 | newRPath=$(../src/patchelf --print-rpath "${SCRATCH}/no-rpath") 16 | if ! echo "$newRPath" | grep -q '/foo:/bar'; then 17 | echo "incomplete RPATH" 18 | exit 1 19 | fi 20 | 21 | cd "${SCRATCH}" && ./no-rpath 22 | -------------------------------------------------------------------------------- /tests/output-flag.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | mkdir -p "${SCRATCH}/libsA" 7 | mkdir -p "${SCRATCH}/libsB" 8 | 9 | cp main "${SCRATCH}"/ 10 | cp libfoo.so "${SCRATCH}/libsA/" 11 | cp libbar.so "${SCRATCH}/libsB/" 12 | 13 | oldRPath=$(../src/patchelf --print-rpath "${SCRATCH}/main") 14 | if test -z "$oldRPath"; then oldRPath="/oops"; fi 15 | 16 | ../src/patchelf --force-rpath --set-rpath "$oldRPath:$(pwd)/${SCRATCH}/libsA:$(pwd)/${SCRATCH}/libsB" "${SCRATCH}/main" --output "${SCRATCH}/main2" 17 | # make sure it copies even when there is nothing to do (because rpath is already set) 18 | ../src/patchelf --force-rpath --set-rpath "$oldRPath:$(pwd)/${SCRATCH}/libsA:$(pwd)/${SCRATCH}/libsB" "${SCRATCH}/main2" --output "${SCRATCH}/main3" 19 | 20 | if test "$(uname)" = FreeBSD; then 21 | LD_LIBRARY_PATH="$(pwd)/${SCRATCH}/libsB" 22 | export LD_LIBRARY_PATH 23 | fi 24 | 25 | exitCode=0 26 | (cd "${SCRATCH}" && ./main2) || exitCode=$? 27 | 28 | if test "$exitCode" != 46; then 29 | echo "bad exit code!" 30 | exit 1 31 | fi 32 | 33 | exitCode=0 34 | (cd "${SCRATCH}" && ./main3) || exitCode=$? 35 | 36 | if test "$exitCode" != 46; then 37 | echo "bad exit code!" 38 | exit 1 39 | fi 40 | -------------------------------------------------------------------------------- /tests/overlapping-segments-after-rounding: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/overlapping-segments-after-rounding -------------------------------------------------------------------------------- /tests/overlapping-segments-after-rounding.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | PATCHELF=$(readlink -f "../src/patchelf") 4 | SCRATCH="scratch/$(basename "$0" .sh)" 5 | READELF=${READELF:-readelf} 6 | 7 | EXEC_NAME="overlapping-segments-after-rounding" 8 | 9 | if test "$(uname -i)" = x86_64 && test "$(uname)" = Linux; then 10 | rm -rf "${SCRATCH}" 11 | mkdir -p "${SCRATCH}" 12 | 13 | cp "${srcdir:?}/${EXEC_NAME}" "${SCRATCH}/" 14 | cd "${SCRATCH}" 15 | 16 | ${PATCHELF} --force-rpath --remove-rpath --output modified1 "${EXEC_NAME}" 17 | 18 | ldd modified1 19 | 20 | ${PATCHELF} --force-rpath --set-rpath "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" --output modified2 modified1 21 | 22 | ldd modified2 23 | fi 24 | -------------------------------------------------------------------------------- /tests/phdr-corruption.ld: -------------------------------------------------------------------------------- 1 | PHDRS 2 | { 3 | headers PT_PHDR PHDRS; 4 | text PT_LOAD FILEHDR PHDRS; 5 | interp PT_INTERP ; 6 | } 7 | 8 | SECTIONS 9 | { 10 | . = SIZEOF_HEADERS; 11 | . = ALIGN(4); 12 | 13 | . = . + 0x1000; 14 | .interp : { *(.interp) } :text :interp 15 | .text : { *(.text) } :text 16 | } 17 | -------------------------------------------------------------------------------- /tests/phdr-corruption.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | PATCHELF="../src/patchelf" 4 | SONAME="phdr-corruption.so" 5 | SCRATCH="scratch/$(basename "$0" .sh)" 6 | SCRATCH_SO="${SCRATCH}/${SONAME}" 7 | READELF=${READELF:-readelf} 8 | 9 | rm -rf "${SCRATCH}" 10 | mkdir -p "${SCRATCH}" 11 | cp "${SONAME}" "${SCRATCH}" 12 | 13 | "${PATCHELF}" --set-rpath "$(pwd)" "${SCRATCH_SO}" 14 | 15 | # Check for PT_PHDR entry VirtAddr corruption 16 | readelfData=$(${READELF} -l "${SCRATCH_SO}" 2>&1) 17 | 18 | if [ "$(echo "$readelfData" | grep -c "PHDR")" != 1 ]; then 19 | # Triggered if PHDR errors appear on stderr 20 | echo "ERROR: Unexpected number of occurences of PHDR in readelf results!" 21 | exit 1 22 | fi 23 | -------------------------------------------------------------------------------- /tests/plain-fail.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | if ./main; then 3 | exit 1 4 | fi 5 | -------------------------------------------------------------------------------- /tests/plain-needed.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | set -e 3 | 4 | SCRATCH=scratch/$(basename "$0" .sh) 5 | MAIN_ELF="${SCRATCH}/main" 6 | 7 | PATCHELF="../src/patchelf" 8 | 9 | rm -rf "${SCRATCH}" 10 | mkdir -p "${SCRATCH}" 11 | cp main "${SCRATCH}"/ 12 | 13 | echo "Confirming main requires libfoo" 14 | ${PATCHELF} --print-needed "${MAIN_ELF}" | grep -q libfoo.so 15 | 16 | echo "Testing --add-needed functionality" 17 | ${PATCHELF} --add-needed bar.so "${MAIN_ELF}" 18 | ${PATCHELF} --print-needed "${MAIN_ELF}" | grep -q bar.so 19 | 20 | echo "Testing --remove-needed functionality" 21 | ${PATCHELF} --remove-needed bar.so "${MAIN_ELF}" 22 | if ${PATCHELF} --print-needed "${MAIN_ELF}" | grep -q bar.so; then 23 | echo "ERROR: --remove-needed did not eliminate bar.so!" 24 | exit 1 25 | fi 26 | -------------------------------------------------------------------------------- /tests/plain-run.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | LD_LIBRARY_PATH=. ./main 3 | exitCode=$? 4 | if test "$exitCode" != 46; then 5 | echo "bad exit code!" 6 | exit 1 7 | fi 8 | -------------------------------------------------------------------------------- /tests/print-execstack.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | PATCHELF=$(readlink -f "../src/patchelf") 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | cp simple "${SCRATCH}"/ 9 | cp simple-execstack "${SCRATCH}"/ 10 | 11 | cd "${SCRATCH}" 12 | 13 | if ! ${PATCHELF} --print-execstack simple | grep -q 'execstack: -'; then 14 | echo "wrong execstack detection" 15 | ${PATCHELF} --print-execstack simple 16 | exit 1 17 | fi 18 | 19 | if ! ${PATCHELF} --print-execstack simple-execstack | grep -q 'execstack: X'; then 20 | echo "wrong execstack detection" 21 | ${PATCHELF} --print-execstack simple-execstack 22 | exit 1 23 | fi 24 | -------------------------------------------------------------------------------- /tests/rename-dynamic-symbols.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | PATCHELF=$(readlink -f "../src/patchelf") 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | full_main_name="${PWD}/many-syms-main" 9 | full_lib_name="${PWD}/libmany-syms.so" 10 | chmod -w "$full_lib_name" "$full_main_name" 11 | 12 | suffix="_special_suffix" 13 | 14 | cd "${SCRATCH}" 15 | 16 | ############################################################################### 17 | # Test that all symbols in the dynamic symbol table will have the expected 18 | # names after renaming. 19 | # Also test that if we rename all symbols back, the symbols are as expected 20 | ############################################################################### 21 | 22 | list_symbols() { 23 | nm -D "$@" | awk '{ print $NF }' | sed '/^ *$/d' 24 | } 25 | 26 | list_symbols "$full_lib_name" | cut -d@ -f1 | sort -u | awk "{printf \"%s %s${suffix}\n\",\$1,\$1}" > map 27 | list_symbols "$full_lib_name" | cut -d@ -f1 | sort -u | awk "{printf \"%s${suffix} %s\n\",\$1,\$1}" > rmap 28 | 29 | ${PATCHELF} --rename-dynamic-symbols map --output libmapped.so "$full_lib_name" 30 | ${PATCHELF} --rename-dynamic-symbols rmap --output libreversed.so libmapped.so 31 | 32 | list_symbols "$full_lib_name" | sort > orig_syms 33 | list_symbols libmapped.so | sort > map_syms 34 | list_symbols libreversed.so | sort > rev_syms 35 | 36 | diff orig_syms rev_syms > diff_orig_syms_rev_syms || exit 1 37 | 38 | # Renamed symbols that match version numbers will be printed with version instead of them being ommited 39 | # CXXABI10 is printed as CXXABI10 40 | # but CXXABI10_renamed is printed as CXXABI10_renamed@@CXXABI10 41 | # awk is used to remove these cases so that we can match the "mapped" symbols to original symbols 42 | sed "s/${suffix}//" map_syms | awk -F @ '{ if ($1 == $2 || $1 == $3) { print $1; } else { print $0; }}' | sort > map_syms_r 43 | diff orig_syms map_syms_r > diff_orig_syms_map_syms_r || exit 1 44 | 45 | ############################################################################### 46 | # Check the relocation tables after renaming 47 | ############################################################################### 48 | 49 | print_relocation_table() { 50 | readelf -W -r "$1" | awk '{ printf "%s\n",$5 }' | cut -f1 -d@ 51 | } 52 | 53 | print_relocation_table "$full_lib_name" > orig_rel 54 | print_relocation_table libmapped.so > map_rel 55 | print_relocation_table libreversed.so > rev_rel 56 | 57 | diff orig_rel rev_rel > diff_orig_rel_rev_rel || exit 1 58 | sed "s/${suffix}//" map_rel > map_rel_r 59 | diff orig_rel map_rel_r > diff_orig_rel_map_rel_r || exit 1 60 | 61 | ############################################################################### 62 | # Test that the hash table is correctly updated. 63 | # For this to work, we need to rename symbols and actually use the library 64 | # Here we: 65 | # 1. Create a map from all symbols in libstdc++.so as "sym sym_special_suffix" 66 | # 2. Copy Patchelf and all of its transitive library dependencies into a new directory 67 | # 3. Rename symbols in Patchelf and all dependencies according to the map 68 | # 4. Run patchelf with the modified dependencies 69 | ############################################################################### 70 | 71 | echo "# Create the map" 72 | list_symbols --defined-only "$full_lib_name" | cut -d@ -f1 | sort -u | awk "{printf \"%s %s${suffix}\n\",\$1,\$1}" > map 73 | 74 | echo "# Copy all dependencies" 75 | mkdir env 76 | cd env 77 | cp "$full_lib_name" "$full_main_name" . 78 | 79 | echo "# Apply renaming" 80 | chmod +w ./* 81 | ${PATCHELF} --rename-dynamic-symbols ../map ./* 82 | 83 | echo "# Run the patched tool and libraries" 84 | env LD_BIND_NOW=1 LD_LIBRARY_PATH="${PWD}" ./many-syms-main 85 | 86 | # Test that other switches still work when --rename-dynamic-symbols has no effect 87 | echo "SYMBOL_THAT_DOESNT_EXIST ANOTHER_NAME" > map 88 | ${PATCHELF} --set-rpath changed_rpath --rename-dynamic-symbols map --output libnewrpath.so "$full_lib_name" 89 | [ "$(${PATCHELF} --print-rpath libnewrpath.so)" = changed_rpath ] || exit 1 90 | 91 | -------------------------------------------------------------------------------- /tests/repeated-updates.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | SCRATCH=scratch/$(basename "$0" .sh) 4 | PATCHELF=$(readlink -f "../src/patchelf") 5 | READELF=${READELF:-readelf} 6 | 7 | rm -rf "${SCRATCH}" 8 | mkdir -p "${SCRATCH}" 9 | 10 | cp simple "${SCRATCH}/" 11 | cp libfoo.so "${SCRATCH}/" 12 | cp libbar.so "${SCRATCH}/" 13 | 14 | cd "${SCRATCH}" 15 | 16 | ${PATCHELF} --add-needed ./libbar.so simple 17 | 18 | ############################################################################### 19 | # Test that repeatedly modifying a string inside a shared library does not 20 | # corrupt it due to the addition of multiple PT_LOAD entries 21 | ############################################################################### 22 | load_segments_before=$(${READELF} -W -l libbar.so | grep -c LOAD) 23 | 24 | for _ in $(seq 1 100) 25 | do 26 | ${PATCHELF} --set-soname ./libbar.so libbar.so 27 | ${PATCHELF} --set-soname libbar.so libbar.so 28 | ./simple || exit 1 29 | done 30 | 31 | load_segments_after=$(${READELF} -W -l libbar.so | grep -c LOAD) 32 | 33 | ############################################################################### 34 | # To be even more strict, check that we don't add too many extra LOAD entries 35 | ############################################################################### 36 | echo "Segments before: ${load_segments_before} and after: ${load_segments_after}" 37 | if [ "${load_segments_after}" -gt $((load_segments_before + 3)) ] 38 | then 39 | exit 1 40 | fi 41 | -------------------------------------------------------------------------------- /tests/replace-add-needed.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | PATCHELF=$(readlink -f "../src/patchelf") 4 | 5 | rm -rf "${SCRATCH}" 6 | mkdir -p "${SCRATCH}" 7 | 8 | cp simple "${SCRATCH}"/ 9 | cp libfoo.so "${SCRATCH}"/ 10 | cp libbar.so "${SCRATCH}"/ 11 | 12 | cd "${SCRATCH}" 13 | 14 | libcldd=$(ldd ./simple | awk '/ => / { print $3 }' | grep -E "(libc(-[0-9.]*)*.so|ld-musl)") 15 | 16 | # We have to set the soname on these libraries 17 | ${PATCHELF} --set-soname libbar.so ./libbar.so 18 | 19 | # Add a libbar.so so we can rewrite it later 20 | ${PATCHELF} --add-needed libbar.so ./simple 21 | 22 | # Make the NEEDED in libfoo the same as simple 23 | # This is a current "bug" in musl 24 | # https://www.openwall.com/lists/musl/2021/12/21/1 25 | ${PATCHELF} --replace-needed libbar.so "$(readlink -f ./libbar.so)" ./libfoo.so 26 | 27 | ${PATCHELF} --replace-needed libc.so.6 "${libcldd}" \ 28 | --replace-needed libbar.so "$(readlink -f ./libbar.so)" \ 29 | --add-needed "$(readlink -f ./libfoo.so)" \ 30 | ./simple 31 | 32 | exitCode=0 33 | ./simple || exitCode=$? 34 | 35 | if test "$exitCode" != 0; then 36 | ldd ./simple 37 | exit 1 38 | fi 39 | -------------------------------------------------------------------------------- /tests/replace-needed.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | 7 | oldLibc=$(../src/patchelf --print-needed big-dynstr | grep -v 'foo\.so') 8 | ../src/patchelf --output "${SCRATCH}/big-needed" --replace-needed "${oldLibc}" long_long_very_long_libc.so.6 --replace-needed libfoo.so lf.so big-dynstr 9 | 10 | if ! ../src/patchelf --print-needed "${SCRATCH}/big-needed" | grep -Fxq "long_long_very_long_libc.so.6"; then 11 | echo "library long_long_very_long_libc.so.6 not found as NEEDED" 12 | ../src/patchelf --print-needed "${SCRATCH}/big-needed" 13 | exit 1 14 | fi 15 | 16 | if ! ../src/patchelf --print-needed "${SCRATCH}/big-needed" | grep -Fxq "lf.so"; then 17 | echo "library lf.so not found as NEEDED" 18 | ../src/patchelf --print-needed "${SCRATCH}/big-needed" 19 | exit 1 20 | fi 21 | -------------------------------------------------------------------------------- /tests/set-empty-rpath.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | 7 | cp simple "${SCRATCH}"/simple 8 | 9 | ../src/patchelf --force-rpath --set-rpath "" "${SCRATCH}/simple" 10 | 11 | "${SCRATCH}"/simple 12 | -------------------------------------------------------------------------------- /tests/set-interpreter-long.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | ./simple 5 | 6 | oldInterpreter=$(../src/patchelf --print-interpreter ./simple) 7 | echo "current interpreter is $oldInterpreter" 8 | 9 | if test "$(uname)" = Linux; then 10 | echo "running with explicit interpreter..." 11 | "$oldInterpreter" ./simple 12 | fi 13 | 14 | rm -rf "${SCRATCH}" 15 | mkdir -p "${SCRATCH}" 16 | 17 | newInterpreter="$(pwd)/${SCRATCH}/iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii" 18 | cp simple "${SCRATCH}/" 19 | ../src/patchelf --set-interpreter "$newInterpreter" "${SCRATCH}/simple" 20 | 21 | echo "running with missing interpreter..." 22 | if "${SCRATCH}"/simple; then 23 | echo "simple works, but it shouldn't" 24 | exit 1 25 | fi 26 | 27 | echo "running with new interpreter..." 28 | ln -s "$oldInterpreter" "$newInterpreter" 29 | "${SCRATCH}"/simple 30 | 31 | if test "$(uname)" = Linux; then 32 | echo "running with explicit interpreter..." 33 | "$oldInterpreter" "${SCRATCH}/simple" 34 | fi 35 | -------------------------------------------------------------------------------- /tests/set-interpreter-same.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | ./simple 5 | 6 | curInterpreter=$(../src/patchelf --print-interpreter ./simple) 7 | echo "current interpreter is $curInterpreter" 8 | 9 | rm -rf "${SCRATCH}" 10 | mkdir -p "${SCRATCH}" 11 | 12 | cp simple "${SCRATCH}"/ 13 | 14 | echo "set the same interpreter as the current one" 15 | before_checksum=$(sha256sum "${SCRATCH}/simple") 16 | ../src/patchelf --set-interpreter "${curInterpreter}" "${SCRATCH}/simple" 17 | after_checksum=$(sha256sum "${SCRATCH}/simple") 18 | 19 | if [ "$before_checksum" != "$after_checksum" ]; then 20 | echo "--set-interpreter should be NOP, but the file has been changed." 21 | exit 1 22 | fi 23 | 24 | "${SCRATCH}/simple" 25 | 26 | dummyInterpreter="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 27 | 28 | echo "set the dummy interpreter" 29 | before_checksum=$(sha256sum "${SCRATCH}/simple") 30 | ../src/patchelf --set-interpreter "${dummyInterpreter}" "${SCRATCH}/simple" 31 | after_checksum=$(sha256sum "${SCRATCH}/simple") 32 | 33 | if [ "$before_checksum" = "$after_checksum" ]; then 34 | echo "--set-interpreter should be run, but the file has not been changed." 35 | exit 1 36 | fi 37 | 38 | if "${SCRATCH}/simple"; then 39 | echo "simple works, but it shouldn't" 40 | exit 1 41 | fi 42 | 43 | echo "set the same interpreter as the current one" 44 | before_checksum=$(sha256sum "${SCRATCH}/simple") 45 | ../src/patchelf --set-interpreter "${dummyInterpreter}" "${SCRATCH}/simple" 46 | after_checksum=$(sha256sum "${SCRATCH}/simple") 47 | 48 | if [ "$before_checksum" != "$after_checksum" ]; then 49 | echo "--set-interpreter should be NOP, but the file has been changed." 50 | exit 1 51 | fi 52 | 53 | if "${SCRATCH}/simple"; then 54 | echo "simple works, but it shouldn't" 55 | exit 1 56 | fi 57 | -------------------------------------------------------------------------------- /tests/set-interpreter-short.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | ./simple 5 | 6 | oldInterpreter=$(../src/patchelf --print-interpreter ./simple) 7 | echo "current interpreter is $oldInterpreter" 8 | 9 | rm -rf "${SCRATCH}" 10 | mkdir -p "${SCRATCH}" 11 | 12 | cp simple "${SCRATCH}"/ 13 | ../src/patchelf --set-interpreter /oops "${SCRATCH}/simple" 14 | 15 | echo "running with missing interpreter..." 16 | if "${SCRATCH}/simple"; then 17 | echo "simple works, but it shouldn't" 18 | exit 1 19 | fi 20 | -------------------------------------------------------------------------------- /tests/set-rpath-library.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | if test "$(uname)" = FreeBSD; then 5 | echo "skipping on FreeBSD" 6 | exit 77 7 | fi 8 | 9 | rm -rf "${SCRATCH}" 10 | mkdir -p "${SCRATCH}" 11 | mkdir -p "${SCRATCH}/libsA" 12 | mkdir -p "${SCRATCH}/libsB" 13 | 14 | cp main-scoped "${SCRATCH}/" 15 | cp libfoo-scoped.so "${SCRATCH}/libsA/" 16 | cp libbar-scoped.so "${SCRATCH}/libsB/" 17 | cp liboveralign.so "${SCRATCH}/" 18 | 19 | oldRPath=$(../src/patchelf --print-rpath "${SCRATCH}"/main-scoped) 20 | if test -z "$oldRPath"; then oldRPath="/oops"; fi 21 | ../src/patchelf --set-rpath "$oldRPath:$(pwd)/${SCRATCH}/libsA:$(pwd)/${SCRATCH}/libsB" "${SCRATCH}/main-scoped" 22 | 23 | # "main" contains libbar in its RUNPATH, but that's ignored when 24 | # resolving libfoo. So libfoo won't find libbar and this will fail. 25 | exitCode=0 26 | (cd "${SCRATCH}" && ./main-scoped) || exitCode=$? 27 | 28 | if test "$exitCode" = 46; then 29 | echo "expected failure" 30 | fi 31 | 32 | # So set an RUNPATH on libfoo as well. 33 | oldRPath=$(../src/patchelf --print-rpath "${SCRATCH}/libsA/libfoo-scoped.so") 34 | if test -z "$oldRPath"; then oldRPath="/oops"; fi 35 | ../src/patchelf --set-rpath "$oldRPath:$(pwd)/${SCRATCH}/libsB" "${SCRATCH}/libsA/libfoo-scoped.so" 36 | 37 | exitCode=0 38 | (cd "${SCRATCH}" && ./main-scoped) || exitCode=$? 39 | 40 | if test "$exitCode" != 46; then 41 | echo "bad exit code!" 42 | exit 1 43 | fi 44 | 45 | # Remove the libbar PATH from main using --shrink-rpath. 46 | ../src/patchelf --shrink-rpath "${SCRATCH}/main-scoped" 47 | if ../src/patchelf --print-rpath "${SCRATCH}/main-scoped" | grep /libsB; then 48 | echo "shrink failed" 49 | exit 1 50 | fi 51 | 52 | # And it should still run. 53 | exitCode=0 54 | (cd "${SCRATCH}" && ./main-scoped) || exitCode=$? 55 | 56 | if test "$exitCode" != 46; then 57 | echo "bad exit code!" 58 | exit 1 59 | fi 60 | 61 | # ALL loads should have the same alignment 62 | lib="${SCRATCH}/liboveralign.so" 63 | ../src/patchelf --set-rpath "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "$lib" 64 | num_alignments=$(${READELF} -W -l "${lib}" | awk '/LOAD/ { print $NF }' | sort -u | wc -l) 65 | echo "$num_alignments" 66 | if test "${num_alignments}" -ne "1"; then 67 | exit 1 68 | fi 69 | -------------------------------------------------------------------------------- /tests/set-rpath-rel-map.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | SCRATCH=scratch/$(basename "$0" .sh) 4 | OBJDUMP=${OBJDUMP:-objdump} 5 | OBJCOPY=${OBJCOPY:-objcopy} 6 | 7 | if ! $OBJDUMP -p main | grep -q MIPS_RLD_MAP_REL; then 8 | echo "No MIPS_RLD_MAP_REL dynamic section entry, skipping" 9 | exit 77 10 | fi 11 | 12 | rm -rf "${SCRATCH}" 13 | mkdir -p "${SCRATCH}" 14 | mkdir -p "${SCRATCH}/libsA" 15 | mkdir -p "${SCRATCH}/libsB" 16 | 17 | cp main "${SCRATCH}/" 18 | cp libfoo.so "${SCRATCH}/libsA/" 19 | cp libbar.so "${SCRATCH}/libsB/" 20 | 21 | # break the main executable by removing .rld_map section 22 | ${OBJCOPY} --remove-section .rld_map "${SCRATCH}/main" 23 | 24 | oldRPath=$(../src/patchelf --print-rpath "${SCRATCH}/main") 25 | if test -z "$oldRPath"; then oldRPath="/oops"; fi 26 | ../src/patchelf --force-rpath --set-rpath "$oldRPath:$(pwd)/${SCRATCH}/libsA:$(pwd)/${SCRATCH}/libsB" "${SCRATCH}/main" 27 | 28 | if test "$(uname)" = FreeBSD; then 29 | LD_LIBRARY_PATH=$(pwd)/"${SCRATCH}"/libsB 30 | export LD_LIBRARY_PATH 31 | fi 32 | 33 | exitCode=0 34 | 35 | (cd "${SCRATCH}" && ./main) || exitCode=$? 36 | 37 | if test "$exitCode" != 46; then 38 | echo "bad exit code!" 39 | exit 1 40 | fi 41 | -------------------------------------------------------------------------------- /tests/set-rpath.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | mkdir -p "${SCRATCH}"/libsA 7 | mkdir -p "${SCRATCH}"/libsB 8 | 9 | cp main "${SCRATCH}"/ 10 | cp libfoo.so "${SCRATCH}/libsA/" 11 | cp libbar.so "${SCRATCH}/libsB/" 12 | 13 | oldRPath=$(../src/patchelf --print-rpath "${SCRATCH}/main") 14 | if test -z "$oldRPath"; then oldRPath="/oops"; fi 15 | ../src/patchelf --force-rpath --set-rpath "$oldRPath:$(pwd)/${SCRATCH}/libsA:$(pwd)/${SCRATCH}/libsB" "${SCRATCH}/main" 16 | 17 | if test "$(uname)" = FreeBSD; then 18 | LD_LIBRARY_PATH="$(pwd)/${SCRATCH}/libsB" 19 | export LD_LIBRARY_PATH 20 | fi 21 | 22 | exitCode=0 23 | (cd "${SCRATCH}" && ./main) || exitCode=$? 24 | 25 | if test "$exitCode" != 46; then 26 | echo "bad exit code!" 27 | exit 1 28 | fi 29 | -------------------------------------------------------------------------------- /tests/shared-rpath.c: -------------------------------------------------------------------------------- 1 | int a_symbol_name; 2 | int foo() { return a_symbol_name; } 3 | -------------------------------------------------------------------------------- /tests/shared-rpath.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | PATCHELF=$(readlink -f "../src/patchelf") 4 | SCRATCH="scratch/$(basename "$0" .sh)" 5 | NM=${NM:-nm} 6 | STRINGS=${STRINGS:-strings} 7 | 8 | LIB_NAME="${PWD}/libshared-rpath.so" 9 | 10 | rm -rf "${SCRATCH}" 11 | mkdir -p "${SCRATCH}" 12 | cd "${SCRATCH}" 13 | 14 | has_x() { 15 | ${STRINGS} "$1" | grep -c "XXXXXXXX" 16 | } 17 | 18 | ${NM} -D "${LIB_NAME}" | grep a_symbol_name 19 | previous_cnt="$(${STRINGS} "${LIB_NAME}" | grep -c a_symbol_name)" 20 | 21 | echo "#### Number of a_symbol_name strings in the library: $previous_cnt" 22 | 23 | echo "#### Rename the rpath to something larger than the original" 24 | # Pathelf should detect that the rpath string is shared with the symbol name string and avoid 25 | # tainting the string with Xs 26 | "${PATCHELF}" --set-rpath a_very_big_rpath_that_is_larger_than_original --output liblarge-rpath.so "${LIB_NAME}" 27 | 28 | echo "#### Checking symbol is still there" 29 | ${NM} -D liblarge-rpath.so | grep a_symbol_name 30 | 31 | echo "#### Checking there are no Xs" 32 | [ "$(has_x liblarge-rpath.so)" -eq 0 ] || exit 1 33 | 34 | current_cnt="$(${STRINGS} liblarge-rpath.so | grep -c a_symbol_name)" 35 | echo "#### Number of a_symbol_name strings in the modified library: $current_cnt" 36 | [ "$current_cnt" -eq "$previous_cnt" ] || exit 1 37 | 38 | echo "#### Rename the rpath to something shorter than the original" 39 | # Pathelf should detect that the rpath string is shared with the symbol name string and avoid 40 | # overwriting the existing string 41 | "${PATCHELF}" --set-rpath shrt_rpth --output libshort-rpath.so "${LIB_NAME}" 42 | 43 | echo "#### Checking symbol is still there" 44 | ${NM} -D libshort-rpath.so | grep a_symbol_name 45 | 46 | echo "#### Number of a_symbol_name strings in the modified library: $current_cnt" 47 | current_cnt="$(${STRINGS} libshort-rpath.so | grep -c a_symbol_name)" 48 | [ "$current_cnt" -eq "$previous_cnt" ] || exit 1 49 | 50 | echo "#### Now liblarge-rpath.so should have its own rpath, so it should be allowed to taint it" 51 | "${PATCHELF}" --set-rpath a_very_big_rpath_that_is_larger_than_original__even_larger --output liblarge-rpath2.so liblarge-rpath.so 52 | [ "$(has_x liblarge-rpath2.so)" -eq 1 ] || exit 1 53 | -------------------------------------------------------------------------------- /tests/short-first-segment.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NixOS/patchelf/523f401584d9584e76c9c77004e7abeb9e6c4551/tests/short-first-segment.gz -------------------------------------------------------------------------------- /tests/short-first-segment.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | PATCHELF=$(readlink -f "../src/patchelf") 4 | SCRATCH="scratch/$(basename "$0" .sh)" 5 | READELF=${READELF:-readelf} 6 | 7 | EXEC_NAME="short-first-segment" 8 | 9 | if test "$(uname -m)" != amd64 || test "$(uname)" != Linux; then 10 | echo "skipping test: amd64 Linux required" 11 | exit 77 12 | fi 13 | 14 | if ! command -v gzip >/dev/null; then 15 | echo "skipping test: gzip not found" 16 | exit 77 17 | fi 18 | 19 | rm -rf "${SCRATCH}" 20 | mkdir -p "${SCRATCH}" 21 | 22 | gzip -c -d "${srcdir:?}/${EXEC_NAME}.gz" > "${SCRATCH}/${EXEC_NAME}" 23 | cd "${SCRATCH}" 24 | 25 | ldd "${EXEC_NAME}" 26 | 27 | 28 | ${PATCHELF} --set-rpath "$(printf '=%.0s' $(seq 1 4096))" --output modified1 "${EXEC_NAME}" 29 | ${PATCHELF} --add-rpath "$(printf '=%.0s' $(seq 1 4096))" modified1 30 | 31 | ldd modified1 32 | 33 | ${PATCHELF} --add-needed "libXcursor.so.1" --output modified2 modified1 34 | ldd modified2 35 | -------------------------------------------------------------------------------- /tests/shrink-rpath-with-allowed-prefixes.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | mkdir -p "${SCRATCH}/libsA" 7 | mkdir -p "${SCRATCH}/libsB" 8 | 9 | cp main "${SCRATCH}"/ 10 | cp libfoo.so libbar.so "${SCRATCH}/libsA/" 11 | cp libfoo.so libbar.so "${SCRATCH}/libsB/" 12 | 13 | oldRPath=$(../src/patchelf --print-rpath "${SCRATCH}/main") 14 | if test -z "$oldRPath"; then oldRPath="/oops"; fi 15 | pathA="$(pwd)/${SCRATCH}/libsA" 16 | pathB="$(pwd)/${SCRATCH}/libsB" 17 | ../src/patchelf --force-rpath --set-rpath "$oldRPath:$pathA:$pathB" "${SCRATCH}/main" 18 | 19 | cp "${SCRATCH}"/main "${SCRATCH}/mainA" 20 | cp "${SCRATCH}"/main "${SCRATCH}/mainB" 21 | 22 | ../src/patchelf --shrink-rpath "${SCRATCH}/main" 23 | ../src/patchelf --shrink-rpath --allowed-rpath-prefixes "$oldRPath:$pathA" "${SCRATCH}/mainA" 24 | ../src/patchelf --shrink-rpath --allowed-rpath-prefixes "$oldRPath:$pathB" "${SCRATCH}/mainB" 25 | 26 | check() { 27 | exe=$1 28 | mustContain=$2 29 | mustNotContain=$3 30 | 31 | rpath=$(../src/patchelf --print-rpath "$exe") 32 | echo "RPATH of $exe after: $rpath" 33 | 34 | if ! echo "$rpath" | grep -q "$mustContain"; then 35 | echo "RPATH didn't contain '$mustContain' when it should have" 36 | exit 1 37 | fi 38 | 39 | if echo "$rpath" | grep -q "$mustNotContain"; then 40 | echo "RPATH contained '$mustNotContain' when it shouldn't have" 41 | exit 1 42 | fi 43 | } 44 | 45 | check "${SCRATCH}/main" "$pathA" "$pathB" 46 | check "${SCRATCH}/mainA" "$pathA" "$pathB" 47 | check "${SCRATCH}/mainB" "$pathB" "$pathA" 48 | -------------------------------------------------------------------------------- /tests/shrink-rpath.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rpath=$(../src/patchelf --print-rpath ./libbar.so) 5 | echo "RPATH before: $rpath" 6 | if ! echo "$rpath" | grep -q /no-such-path; then 7 | echo "incomplete RPATH" 8 | exit 1 9 | fi 10 | 11 | rm -rf "${SCRATCH}" 12 | mkdir -p "${SCRATCH}" 13 | cp libbar.so "${SCRATCH}"/ 14 | ../src/patchelf --shrink-rpath "${SCRATCH}/libbar.so" 15 | 16 | rpath=$(../src/patchelf --print-rpath "${SCRATCH}/libbar.so") 17 | echo "RPATH after: $rpath" 18 | if echo "$rpath" | grep -q /no-such-path; then 19 | echo "RPATH not shrunk" 20 | exit 1 21 | fi 22 | 23 | cp libfoo.so "${SCRATCH}/" 24 | 25 | exitCode=0 26 | cd "${SCRATCH}" && LD_LIBRARY_PATH=. ../../main || exitCode=$? 27 | 28 | if test "$exitCode" != 46; then 29 | echo "bad exit code!" 30 | exit 1 31 | fi 32 | -------------------------------------------------------------------------------- /tests/simple.c: -------------------------------------------------------------------------------- 1 | #include <stdio.h> 2 | 3 | char buf[16 * 1024 * 1024]; 4 | 5 | int main(int argc, char * * argv) 6 | { 7 | printf("Hello World\n"); 8 | return 0; 9 | } 10 | -------------------------------------------------------------------------------- /tests/soname.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | 7 | cp libsimple.so "${SCRATCH}/" 8 | 9 | # set an initial DT_SONAME entry 10 | ../src/patchelf --set-soname libsimple.so.1.0 "${SCRATCH}/libsimple.so" 11 | newSoname=$(../src/patchelf --print-soname "${SCRATCH}/libsimple.so") 12 | if test "$newSoname" != libsimple.so.1.0; then 13 | echo "failed --set-soname test. Expected newSoname: libsimple.so.1.0, got: $newSoname" 14 | exit 1 15 | fi 16 | 17 | # print DT_SONAME 18 | soname=$(../src/patchelf --print-soname "${SCRATCH}/libsimple.so") 19 | if test "$soname" != libsimple.so.1.0; then 20 | echo "failed --print-soname test. Expected soname: libsimple.so.1.0, got: $soname" 21 | exit 1 22 | fi 23 | 24 | # replace DT_SONAME entry 25 | ../src/patchelf --set-soname libsimple.so.1.1 "${SCRATCH}/libsimple.so" 26 | newSoname=$(../src/patchelf --print-soname "${SCRATCH}/libsimple.so") 27 | if test "$newSoname" != libsimple.so.1.1; then 28 | echo "failed --set-soname test. Expected newSoname: libsimple.so.1.1, got: $newSoname" 29 | exit 1 30 | fi 31 | -------------------------------------------------------------------------------- /tests/too-many-strtab.c: -------------------------------------------------------------------------------- 1 | int main(){ return 0; } 2 | -------------------------------------------------------------------------------- /tests/too-many-strtab.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | SCRATCH=scratch/$(basename "$0" .sh) 3 | 4 | rm -rf "${SCRATCH}" 5 | mkdir -p "${SCRATCH}" 6 | 7 | cp libtoomanystrtab.so "${SCRATCH}"/ 8 | 9 | # Set a RUNPATH on the library 10 | ../src/patchelf --set-rpath "\$ORIGIN" "${SCRATCH}/libtoomanystrtab.so" 11 | 12 | # Check that patchelf is able to patch it again without crashing. Previously, 13 | # it will wrongly identify the lib as a static object because there was no 14 | # .dynamic section 15 | exitCode=0 16 | (../src/patchelf --set-rpath "\$ORIGIN" "${SCRATCH}/libtoomanystrtab.so") || exitCode=$? 17 | if test "$exitCode" != 0; then 18 | echo "bad exit code!" 19 | exit 1 20 | fi 21 | 22 | -------------------------------------------------------------------------------- /tests/too-many-strtab2.s: -------------------------------------------------------------------------------- 1 | /* 2 | * Create additional .shstrtab section 3 | */ 4 | .section ".shstrtab", "", %3 5 | .byte 0 6 | -------------------------------------------------------------------------------- /tests/void.c: -------------------------------------------------------------------------------- 1 | int main() 2 | { 3 | return 0; 4 | } 5 | -------------------------------------------------------------------------------- /version: -------------------------------------------------------------------------------- 1 | 0.18.0 2 | --------------------------------------------------------------------------------