{"id":13730882,"url":"https://github.com/GrapheneOS/platform_bionic","last_synced_at":"2025-05-08T03:32:19.105Z","repository":{"id":5310356,"uuid":"48075851","full_name":"GrapheneOS/platform_bionic","owner":"GrapheneOS","description":"Hardened Android standard C library. Some of the past hardening has not yet been ported from Marshmallow, Nougat and Oreo to this Android Pie repository. Most is available via archived tags in https://github.com/AndroidHardeningArchive/platform_bionic (check both the most recent Oreo and Nougat tags).","archived":false,"fork":false,"pushed_at":"2024-08-03T04:22:16.000Z","size":55569,"stargazers_count":94,"open_issues_count":0,"forks_count":33,"subscribers_count":12,"default_branch":"14","last_synced_at":"2024-08-04T02:09:51.109Z","etag":null,"topics":["android","grapheneos","libc","security"],"latest_commit_sha":null,"homepage":"https://grapheneos.org/","language":"Assembly","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GrapheneOS.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null},"funding":{"github":"thestinger","custom":"https://grapheneos.org/donate"}},"created_at":"2015-12-15T23:55:35.000Z","updated_at":"2024-08-04T02:09:51.110Z","dependencies_parsed_at":"2023-02-18T17:16:03.193Z","dependency_job_id":"48a41b7e-5f23-47ee-81a9-c9be23006b41","html_url":"https://github.com/GrapheneOS/platform_bionic","commit_stats":null,"previous_names":[],"tags_count":607,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GrapheneOS%2Fplatform_bionic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GrapheneOS%2Fplatform_bionic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GrapheneOS%2Fplatform_bionic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GrapheneOS%2Fplatform_bionic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GrapheneOS","download_url":"https://codeload.github.com/GrapheneOS/platform_bionic/tar.gz/refs/heads/14","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224695787,"owners_count":17354480,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["android","grapheneos","libc","security"],"created_at":"2024-08-03T02:01:20.849Z","updated_at":"2024-11-14T21:31:49.002Z","avatar_url":"https://github.com/GrapheneOS.png","language":"Assembly","readme":"# bionic\n\n[bionic](https://en.wikipedia.org/wiki/Bionic_(software)) is Android's\nC library, math library, and dynamic linker.\n\n# Using bionic as an app developer\n\nSee the [user documentation](docs/).\n\n# Working on bionic itself\n\nThis documentation is about making changes to bionic itself.\n\n## What are the big pieces of bionic?\n\n#### libc/ --- libc.so, libc.a\n\nThe C library. Stuff like `fopen(3)` and `kill(2)`.\n\n#### libm/ --- libm.so, libm.a\n\nThe math library. Traditionally Unix systems kept stuff like `sin(3)` and\n`cos(3)` in a separate library to save space in the days before shared\nlibraries.\n\n#### libdl/ --- libdl.so\n\nThe dynamic linker interface library. This is actually just a bunch of stubs\nthat the dynamic linker replaces with pointers to its own implementation at\nruntime. This is where stuff like `dlopen(3)` lives.\n\n#### libstdc++/ --- libstdc++.so\n\nThe C++ ABI support functions. The C++ compiler doesn't know how to implement\nthread-safe static initialization and the like, so it just calls functions that\nare supplied by the system. Stuff like `__cxa_guard_acquire` and\n`__cxa_pure_virtual` live here.\n\n#### linker/ --- /system/bin/linker and /system/bin/linker64\n\nThe dynamic linker. When you run a dynamically-linked executable, its ELF file\nhas a `DT_INTERP` entry that says \"use the following program to start me\".  On\nAndroid, that's either `linker` or `linker64` (depending on whether it's a\n32-bit or 64-bit executable). It's responsible for loading the ELF executable\ninto memory and resolving references to symbols (so that when your code tries to\njump to `fopen(3)`, say, it lands in the right place).\n\n#### tests/ --- unit tests\n\nThe `tests/` directory contains unit tests. Roughly arranged as one file per\npublicly-exported header file. `tests/headers/` contains compile-only tests\nthat just check that things are _in_ the headers, whereas the \"real\" tests\ncheck actual _behavior_.\n\n#### benchmarks/ --- benchmarks\n\nThe `benchmarks/` directory contains benchmarks, with its own [documentation](benchmarks/README.md).\n\n\n## What's in libc/?\n\n```\nlibc/\n  arch-arm/\n  arch-arm64/\n  arch-common/\n  arch-x86/\n  arch-x86_64/\n    # Each architecture has its own subdirectory for stuff that isn't shared\n    # because it's architecture-specific. There will be a .mk file in here that\n    # drags in all the architecture-specific files.\n    bionic/\n      # Every architecture needs a handful of machine-specific assembler files.\n      # They live here.\n    string/\n      # Most architectures have a handful of optional assembler files\n      # implementing optimized versions of various routines. The \u003cstring.h\u003e\n      # functions are particular favorites.\n    syscalls/\n      # The syscalls directories contain script-generated assembler files.\n      # See 'Adding system calls' later.\n\n  include/\n    # The public header files on everyone's include path. These are a mixture of\n    # files written by us and files taken from BSD.\n\n  kernel/\n    # The kernel uapi header files. The \"libc\" headers that developers actually\n    # use are a mixture of headers provided by the C library itself (which,\n    # for bionic, are in bionic/libc/include/) and headers provided by the\n    # kernel. This is because ISO C and POSIX will say things like \"there is\n    # a constant called PROT_NONE\" or \"there is a type called struct stat,\n    # and it contains a field called st_size\", but they won't necessarily say\n    # what _value_ that constant has, or what _order_ the fields in a type\n    # are in. Those are left to individual kernels' ABIs. In an effort to --\n    # amongst other things, see https://lwn.net/Articles/507794/ for more\n    # background -- reduce copy \u0026 paste, the Linux kernel makes all the types\n    # and constants that make up the \"userspace API\" (uapi) available as\n    # headers separate from their internal-use headers (which contain all kinds\n    # of extra stuff that isn't available to userspace). We import the latest\n    # released kernel's uapi headers in external/kernel-headers/, but we don't\n    # use those headers directly in bionic. The bionic/libc/kernel/ directory\n    # contains scrubbed copies of the originals from external/kernel-headers/.\n    # The generate_uapi_headers.sh script should be used to go from a kernel\n    # tree to external/kernel-headers/ --- this takes care of the\n    # architecture-specific details. The update_all.py script should then be\n    # used to regenerate bionic's copy from external/kernel-headers/.\n    # The files in bionic must not be edited directly because any local changes\n    # will be overwritten by the next update. \"Updating kernel header files\"\n    # below has more information on this process.\n\n  private/\n    # These are private header files meant for use within bionic itself.\n\n  dns/\n    # Contains the DNS resolver (originates from NetBSD code).\n\n  upstream-freebsd/\n  upstream-netbsd/\n  upstream-openbsd/\n    # These directories contain upstream source with no local changes.\n    # Any time we can just use a BSD implementation of something unmodified,\n    # we should. Ideally these should probably have been three separate git\n    # projects in external/, but they're here instead mostly by historical\n    # accident (because it wouldn't have been easy to import just the tiny\n    # subset of these operating systems that -- unlike Android -- just have\n    # one huge repository rather than lots of little ones and a mechanism\n    # like our `repo` tool).\n    # The structure under these directories mimics the relevant upstream tree,\n    # but in order to actually be able to compile this code in our tree\n    # _without_ making modifications to the source files directly, we also\n    # have the following subdirectories in each one that aren't upstream:\n    android/\n      include/\n        # This is where we keep the hacks necessary to build BSD source\n        # in our world. The *-compat.h files are automatically included\n        # using -include, but we also provide equivalents for missing\n        # header/source files needed by the BSD implementation.\n\n  bionic/\n    # This is the biggest mess. The C++ files are files we own, typically\n    # because the Linux kernel interface is sufficiently different that we\n    # can't use any of the BSD implementations. The C files are usually\n    # legacy mess that needs to be sorted out, either by replacing it with\n    # current upstream source in one of the upstream directories or by\n    # switching the file to C++ and cleaning it up.\n\n  malloc_debug/\n    # The code that implements the functionality to enable debugging of\n    # native allocation problems.\n\n  stdio/\n    # These are legacy files of dubious provenance. We're working to clean\n    # this mess up, and this directory should disappear.\n\n  tools/\n    # Various tools used to maintain bionic.\n\n  tzcode/\n    # A modified superset of the IANA tzcode. Most of the modifications relate\n    # to Android's use of a single file (with corresponding index) to contain\n    # timezone data.\n  zoneinfo/\n    # Android-format timezone data.\n    # See 'Updating tzdata' later.\n```\n\n\n## Adding libc wrappers for system calls\n\nThe first question you should ask is \"should I add a libc wrapper for\nthis system call?\". The answer is usually \"no\".\n\nThe answer is \"yes\" if the system call is part of the POSIX standard.\n\nThe answer is probably \"yes\" if the system call has a wrapper in at\nleast one other C library (typically glibc/musl or Apple's libc).\n\nThe answer may be \"yes\" if the system call has three/four distinct\nusers in different projects, and there isn't a more specific higher-level\nlibrary that would make more sense as the place to add the wrapper.\n\nIn all other cases, you should use\n[syscall(3)](http://man7.org/linux/man-pages/man2/syscall.2.html) instead.\n\nAdding a system call usually involves:\n\n  1. Add an entry (or entries, in some cases) to SYSCALLS.TXT.\n     See SYSCALLS.TXT itself for documentation on the format.\n     See also the notes below for how to deal with tricky cases like `off_t`.\n  2. Find the right header file to work in by looking up your system call\n     on [man7.org](https://man7.org/linux/man-pages/dir_section_2.html).\n     (If there's no header file given, see the points above about whether we\n     should really be adding this or not!)\n  3. Add constants (and perhaps types) to the appropriate header file.\n     Note that you should check to see whether the constants are already in\n     kernel uapi header files, in which case you just need to make sure that\n     the appropriate header file in libc/include/ `#include`s the relevant\n     `linux/` file or files.\n  4. Add function declarations to the appropriate header file. Don't forget\n     to include the appropriate `__INTRODUCED_IN()`, with the right API level\n     for the first release your system call wrapper will be in. See\n     libc/include/android/api_level.h for the API levels.\n     If the header file doesn't exist, copy all of libc/include/sys/sysinfo.h\n     into your new file --- it's a good short example to start from.\n\n     Note also our style for naming arguments: always use two leading\n     underscores (so developers are free to use any of the unadorned names as\n     macros without breaking things), avoid abbreviations, and ideally try to\n     use the same name as an existing system call (to reduce the amount of\n     English vocabulary required by people who just want to use the function\n     signatures). If there's a similar function already in the C library,\n     check what names it's used. Finally, prefer the `void*` orthography we\n     use over the `void *` you'll see on man7.org.)\n  5. Add basic documentation to the header file. Again, the existing\n     libc/include/sys/sysinfo.h is a good short example that shows the\n     expected style.\n\n     Most of the detail should actually be left to the man7.org page, with\n     only a brief one-sentence explanation (usually based on the description\n     in the NAME section of the man page) in our documentation. Always\n     include the return value/error reporting details (you can find out\n     what the system call returns from the RETURN VALUE of the man page),\n     but try to match the wording and style wording from _our_ existing\n     documentation; we're trying to minimize the amount of English readers\n     need to understand by using the exact same wording where possible).\n     Explicitly say which version of Android the function was added to in\n     the documentation because the documentation generation tool doesn't yet\n     understand `__INTRODUCED_IN()`.\n\n     Explicitly call out any Android-specific changes/additions/limitations\n     because they won't be on the man7.org page.\n  6. Add the function name to the correct section in libc/libc.map.txt; it'll\n     be near the end of the file. You may need to add a new section if you're\n     the first to add a system call to this version of Android.\n  7. Add a basic test. Don't try to test everything; concentrate on just testing\n     the code that's actually in *bionic*, not all the functionality that's\n     implemented in the kernel. For simple syscalls, that's just the\n     auto-generated argument and return value marshalling.\n\n     Add a test in the right file in tests/. We have one file per header, so if\n     your system call is exposed in \u003cunistd.h\u003e, for example, your test would go\n     in tests/unistd_test.cpp.\n\n     A trivial test that deliberately supplies an invalid argument helps check\n     that we're generating the right symbol and have the right declaration in\n     the header file, and that the change to libc.map.txt from step 5 is\n     correct. (You can use strace(1) manually to confirm that the correct\n     system call is being made.)\n\n     For testing the *kernel* side of things, we should prefer to rely on\n     https://github.com/linux-test-project/ltp for kernel testing, but you'll\n     want to check that external/ltp does contain tests for the syscall you're\n     adding. Also check that external/ltp is using the libc wrapper for the\n     syscall rather than calling it \"directly\" via syscall(3)!\n\nSome system calls are harder than others. The most common problem is a 64-bit\nargument such as `off64_t` (a *pointer* to a 64-bit argument is fine, since\npointers are always the \"natural\" size for the architecture regardless of the\nsize of the thing they point to). Whenever you have a function that takes\n`off_t` or `off64_t`, you'll need to consider whether you actually need a foo()\nand a foo64(), and whether they will use the same underlying system call or are\nimplemented as two different system calls. It's usually easiest to find a\nsimilar system call and copy and paste from that. You'll definitely need to test\nboth on 32-bit and 64-bit. (These special cases warrant more testing than the\neasy cases, even if only manual testing with strace. Sadly it isn't always\nfeasible to write a working test for the interesting cases -- offsets larger\nthan 2GiB, say -- so you may end up just writing a \"meaningless\" program whose\nonly purpose is to give you patterns to look for when run under strace(1).)\n\nA general example of adding a system call:\nhttps://android-review.googlesource.com/c/platform/bionic/+/2073827\n\n### Debugging tips\n1. Key error for a new codename in libc/libc.map.txt\n\ne.g. what you add in libc/libc.map.txt is:\n\n```\nLIBC_V { # introduced=Vanilla\n  global:\n    xxx; // the new system call you add\n} LIBC_U;\n```\n\nThe error output is:\n\n```\nTraceback (most recent call last):\n  File \"/path/tp/out/soong/.temp/Soong.python_qucjwd7g/symbolfile/__init__.py\", line 171,\n  in decode_api_level_tag\n    decoded = str(decode_api_level(value, api_map))\n  File \"/path/to/out/soong/.temp/Soong.python_qucjwd7g/symbolfile/__init__.py\", line 157,\n  in decode_api_level\n    return api_map[api]\nKeyError: 'Vanilla'\n```\n\nSolution: Ask in the team and wait for the update.\n\n2. Use of undeclared identifier of the new system call in the test\n\nPossible Solution: Check everything ready in the files mentioned above first.\nMaybe glibc matters. Follow the example and try #if defined(__GLIBC__).\n\n## Updating kernel header files\n\nAs mentioned above, this is currently a two-step process:\n\n  1. Use generate_uapi_headers.sh to go from a Linux source tree to appropriate\n     contents for external/kernel-headers/.\n  2. Run update_all.py to scrub those headers and import them into bionic.\n\nNote that if you're actually just trying to expose device-specific headers to\nbuild your device drivers, you shouldn't modify bionic. Instead use\n`TARGET_DEVICE_KERNEL_HEADERS` and friends described in [config.mk](https://android.googlesource.com/platform/build/+/main/core/config.mk#186).\n\n\n## Updating tzdata\n\nThis is handled by the libcore team, because they own icu, and that needs to be\nupdated in sync with bionic). See\n[system/timezone/README.android](https://android.googlesource.com/platform/system/timezone/+/main/README.android).\n\n\n## Verifying changes\n\nIf you make a change that is likely to have a wide effect on the tree (such as a\nlibc header change), you should run `make checkbuild`. A regular `make` will\n_not_ build the entire tree; just the minimum number of projects that are\nrequired for the device. Tests, additional developer tools, and various other\nmodules will not be built. Note that `make checkbuild` will not be complete\neither, as `make tests` covers a few additional modules, but generally speaking\n`make checkbuild` is enough.\n\n\n## Running the tests\n\nThe tests are all built from the tests/ directory. There is a separate\ndirectory `benchmarks/` containing benchmarks, and that has its own\ndocumentation on [running the benchmarks](benchmarks/README.md).\n\n### Device tests\n\n    $ mma # In $ANDROID_ROOT/bionic.\n    $ adb root \u0026\u0026 adb remount \u0026\u0026 adb sync\n    $ adb shell /data/nativetest/bionic-unit-tests/bionic-unit-tests\n    $ adb shell \\\n        /data/nativetest/bionic-unit-tests-static/bionic-unit-tests-static\n    # Only for 64-bit targets\n    $ adb shell /data/nativetest64/bionic-unit-tests/bionic-unit-tests\n    $ adb shell \\\n        /data/nativetest64/bionic-unit-tests-static/bionic-unit-tests-static\n\nNote that we use our own custom gtest runner that offers a superset of the\noptions documented at\n\u003chttps://github.com/google/googletest/blob/main/docs/advanced.md#running-test-programs-advanced-options\u003e,\nin particular for test isolation and parallelism (both on by default).\n\n### Device tests via CTS\n\nMost of the unit tests are executed by CTS. By default, CTS runs as\na non-root user, so the unit tests must also pass when not run as root.\nSome tests cannot do any useful work unless run as root. In this case,\nthe test should check `getuid() == 0` and do nothing otherwise (typically\nwe log in this case to prevent accidents!). Obviously, if the test can be\nrewritten to not require root, that's an even better solution.\n\nCurrently, the list of bionic CTS tests is generated at build time by\nrunning a host version of the test executable and dumping the list of\nall tests. In order for this to continue to work, all architectures must\nhave the same number of tests, and the host version of the executable\nmust also have the same number of tests.\n\nRunning the gtests directly is orders of magnitude faster than using CTS,\nbut in cases where you really have to run CTS:\n\n    $ make cts # In $ANDROID_ROOT.\n    $ adb unroot # Because real CTS doesn't run as root.\n    # This will sync any *test* changes, but not *code* changes:\n    $ cts-tradefed \\\n        run singleCommand cts --skip-preconditions -m CtsBionicTestCases\n\n### Host tests\n\nThe host tests require that you have `lunch`ed either an x86 or x86_64 target.\nNote that due to ABI limitations (specifically, the size of pthread_mutex_t),\n32-bit bionic requires PIDs less than 65536. To enforce this, set /proc/sys/kernel/pid_max\nto 65536.\n\n    $ ./tests/run-on-host.sh 32\n    $ ./tests/run-on-host.sh 64   # For x86_64-bit *targets* only.\n\nYou can supply gtest flags as extra arguments to this script.\n\n### Against glibc\n\nAs a way to check that our tests do in fact test the correct behavior (and not\njust the behavior we think is correct), it is possible to run the tests against\nthe host's glibc.\n\n    $ ./tests/run-on-host.sh glibc\n\n### Against musl\n\nAnother way to verify test behavior is to run against musl on the host. glibc\nmusl don't always match, so this can be a good way to find the more complicated\ncorners of the spec. If they *do* match, bionic probably should too!\n\n    $ OUT_DIR=$(ANDROID_BUILD_TOP)/musl-out ./tests/run-on-host.sh musl\n\nNote: the alternate OUT_DIR is used to avoid causing excessive rebuilding when\nswitching between glibc and musl. The first musl test run will be expensive\nbecause it will not reuse any already built artifacts, but subsequent runs will\nbe cheaper than if you hadn't used it.\n\n## Gathering test coverage\n\nTo get test coverage for bionic, use `//bionic/build/coverage.sh`. Before\nrunning, follow the instructions at the top of the file to rebuild bionic with\ncoverage instrumentation.\n\n## Attaching GDB to the tests\n\nBionic's test runner will run each test in its own process by default to prevent\ntests failures from impacting other tests. This also has the added benefit of\nrunning them in parallel, so they are much faster.\n\nHowever, this also makes it difficult to run the tests under GDB. To prevent\neach test from being forked, run the tests with the flag `--no-isolate`.\n\n\n## 32-bit ABI bugs\n\nSee [32-bit ABI bugs](docs/32-bit-abi.md).\n","funding_links":["https://github.com/sponsors/thestinger","https://grapheneos.org/donate"],"categories":["C++"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGrapheneOS%2Fplatform_bionic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FGrapheneOS%2Fplatform_bionic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGrapheneOS%2Fplatform_bionic/lists"}