Merge "Update to v6.0 kernel headers."
diff --git a/libc/Android.bp b/libc/Android.bp
index d985c81..6042929 100644
--- a/libc/Android.bp
+++ b/libc/Android.bp
@@ -197,6 +197,9 @@
         arm64: {
             srcs: ["arch-arm64/bionic/__set_tls.c"],
         },
+        riscv64: {
+            srcs: ["arch-riscv64/bionic/__set_tls.c"],
+        },
         x86: {
             srcs: [
                 "arch-x86/bionic/__libc_init_sysinfo.cpp",
@@ -661,6 +664,17 @@
                 "upstream-openbsd/lib/libc/string/strncmp.c",
             ],
         },
+        riscv64: {
+            srcs: [
+                "arch-riscv64/string/memset_chk.c",
+                "upstream-freebsd/lib/libc/string/memcmp.c",
+                "upstream-freebsd/lib/libc/string/memcpy.c",
+                "upstream-freebsd/lib/libc/string/memmove.c",
+                "upstream-freebsd/lib/libc/string/memset.c",
+                "upstream-openbsd/lib/libc/string/strcmp.c",
+                "upstream-openbsd/lib/libc/string/strlen.c",
+            ],
+        },
         x86: {
             exclude_srcs: [
                 "upstream-openbsd/lib/libc/string/memchr.c",
@@ -906,6 +920,16 @@
             ],
         },
 
+        riscv64: {
+            srcs: [
+                "arch-riscv64/bionic/__bionic_clone.S",
+                "arch-riscv64/bionic/_exit_with_stack_teardown.S",
+                "arch-riscv64/bionic/setjmp.S",
+                "arch-riscv64/bionic/syscall.S",
+                "arch-riscv64/bionic/vfork.S",
+            ],
+        },
+
         x86: {
             srcs: [
                 "arch-x86/generic/string/memcmp.S",
@@ -1294,9 +1318,6 @@
     srcs: ["SYSCALLS.TXT"],
     tools: ["gensyscalls"],
     cmd: "$(location gensyscalls) arm $(in) > $(out)",
-    bazel_module: {
-        bp2build_available: true,
-    }
 }
 
 genrule {
@@ -1305,9 +1326,14 @@
     srcs: ["SYSCALLS.TXT"],
     tools: ["gensyscalls"],
     cmd: "$(location gensyscalls) arm64 $(in) > $(out)",
-    bazel_module: {
-        bp2build_available: true,
-    },
+}
+
+genrule {
+    name: "syscalls-riscv64.S",
+    out: ["syscalls-riscv64.S"],
+    srcs: ["SYSCALLS.TXT"],
+    tools: ["gensyscalls"],
+    cmd: "$(location gensyscalls) riscv64 $(in) > $(out)",
 }
 
 genrule {
@@ -1316,9 +1342,6 @@
     srcs: ["SYSCALLS.TXT"],
     tools: ["gensyscalls"],
     cmd: "$(location gensyscalls) x86 $(in) > $(out)",
-    bazel_module: {
-        bp2build_available: true,
-    },
 }
 
 genrule {
@@ -1327,9 +1350,6 @@
     srcs: ["SYSCALLS.TXT"],
     tools: ["gensyscalls"],
     cmd: "$(location gensyscalls) x86_64 $(in) > $(out)",
-    bazel_module: {
-        bp2build_available: true,
-    },
 }
 
 cc_library_static {
@@ -1342,6 +1362,9 @@
         arm64: {
             srcs: [":syscalls-arm64.S"],
         },
+        riscv64: {
+            srcs: [":syscalls-riscv64.S"],
+        },
         x86: {
             srcs: [":syscalls-x86.S"],
         },
@@ -1622,7 +1645,6 @@
         "bionic/NetdClient.cpp",
         "arch-common/bionic/crtend_so.S",
     ],
-    bazel_module: { bp2build_available: true },
 }
 
 filegroup {
@@ -1633,7 +1655,6 @@
         "bionic/malloc_common.cpp",
         "bionic/malloc_limit.cpp",
     ],
-    bazel_module: { bp2build_available: true },
 }
 
 filegroup {
@@ -1642,7 +1663,6 @@
         "arch-arm/bionic/exidx_dynamic.c",
         "arch-arm/bionic/atexit_legacy.c",
     ],
-    bazel_module: { bp2build_available: true },
 }
 
 // ========================================================
@@ -1740,6 +1760,15 @@
                 keep_symbols: true,
             },
         },
+        riscv64: {
+            version_script: ":libc.riscv64.map",
+
+            // Leave the symbols in the shared library so that stack unwinders can produce
+            // meaningful name resolution.
+            strip: {
+                keep_symbols: true,
+            },
+        },
         x86: {
             // TODO: This is to work around b/24465209. Remove after root cause is fixed.
             pack_relocations: false,
@@ -1804,7 +1833,6 @@
     srcs: ["libc.map.txt"],
     tools: ["generate-version-script"],
     cmd: "$(location generate-version-script) arm $(in) $(out)",
-    bazel_module: { bp2build_available: true },
 }
 
 genrule {
@@ -1813,7 +1841,14 @@
     srcs: ["libc.map.txt"],
     tools: ["generate-version-script"],
     cmd: "$(location generate-version-script) arm64 $(in) $(out)",
-    bazel_module: { bp2build_available: true },
+}
+
+genrule {
+    name: "libc.riscv64.map",
+    out: ["libc.riscv64.map"],
+    srcs: ["libc.map.txt"],
+    tools: ["generate-version-script"],
+    cmd: "$(location generate-version-script) riscv64 $(in) $(out)",
 }
 
 genrule {
@@ -1822,7 +1857,6 @@
     srcs: ["libc.map.txt"],
     tools: ["generate-version-script"],
     cmd: "$(location generate-version-script) x86 $(in) $(out)",
-    bazel_module: { bp2build_available: true },
 }
 
 genrule {
@@ -1831,7 +1865,6 @@
     srcs: ["libc.map.txt"],
     tools: ["generate-version-script"],
     cmd: "$(location generate-version-script) x86_64 $(in) $(out)",
-    bazel_module: { bp2build_available: true },
 }
 
 // Headers that only other parts of the platform can include.
@@ -1871,7 +1904,6 @@
         "//apex_available:platform",
         "//apex_available:anyapex",
     ],
-    bazel_module: { bp2build_available: true },
 }
 
 cc_library_headers {
@@ -1921,6 +1953,9 @@
         arm64: {
             export_system_include_dirs: ["kernel/uapi/asm-arm64"],
         },
+        riscv64: {
+            export_system_include_dirs: ["kernel/uapi/asm-riscv"],
+        },
         x86: {
             export_system_include_dirs: ["kernel/uapi/asm-x86"],
         },
@@ -1928,7 +1963,6 @@
             export_system_include_dirs: ["kernel/uapi/asm-x86"],
         },
     },
-    bazel_module: { bp2build_available: true },
 }
 
 cc_library_headers {
@@ -1976,7 +2010,6 @@
             export_header_lib_headers: ["libc_llndk_headers"],
         },
     },
-    bazel_module: { bp2build_available: true },
 }
 
 // ========================================================
@@ -2017,6 +2050,9 @@
         arm64: {
             version_script: ":libstdc++.arm64.map",
         },
+        riscv64: {
+            version_script: ":libstdc++.riscv64.map",
+        },
         x86: {
             pack_relocations: false,
             ldflags: ["-Wl,--hash-style=both"],
@@ -2045,6 +2081,14 @@
 }
 
 genrule {
+    name: "libstdc++.riscv64.map",
+    out: ["libstdc++.riscv64.map"],
+    srcs: ["libstdc++.map.txt"],
+    tools: ["generate-version-script"],
+    cmd: "$(location generate-version-script) riscv64 $(in) $(out)",
+}
+
+genrule {
     name: "libstdc++.x86.map",
     out: ["libstdc++.x86.map"],
     srcs: ["libstdc++.map.txt"],
@@ -2127,8 +2171,6 @@
     srcs: ["arch-common/bionic/crtbrand.S"],
 
     defaults: ["crt_so_defaults"],
-
-    bazel_module: { bp2build_available: true },
 }
 
 cc_object {
@@ -2140,8 +2182,6 @@
     objs: [
         "crtbrand",
     ],
-
-    bazel_module: { bp2build_available: true },
 }
 
 cc_object {
@@ -2153,8 +2193,6 @@
     srcs: ["arch-common/bionic/crtend_so.S"],
 
     defaults: ["crt_so_defaults"],
-
-    bazel_module: { bp2build_available: true },
 }
 
 cc_object {
@@ -2172,8 +2210,6 @@
     defaults: ["crt_defaults"],
     // When using libc.a, we're using the latest library regardless of target API level.
     min_sdk_version: "current",
-
-    bazel_module: { bp2build_available: true },
 }
 
 cc_object {
@@ -2196,8 +2232,6 @@
         },
     },
     defaults: ["crt_defaults"],
-
-    bazel_module: { bp2build_available: true },
 }
 
 cc_object {
@@ -2211,8 +2245,6 @@
     srcs: ["arch-common/bionic/crtend.S"],
 
     defaults: ["crt_defaults"],
-
-    bazel_module: { bp2build_available: true },
 }
 
 cc_library_static {
@@ -2302,6 +2334,14 @@
 }
 
 ndk_headers {
+    name: "libc_asm_riscv64",
+    from: "kernel/uapi/asm-riscv",
+    to: "riscv64-linux-android",
+    srcs: ["kernel/uapi/asm-riscv/**/*.h"],
+    license: "NOTICE",
+}
+
+ndk_headers {
     name: "libc_asm_x86",
     from: "kernel/uapi/asm-x86",
     to: "i686-linux-android",
@@ -2330,6 +2370,7 @@
         "libc_kernel_android_scsi",
         "libc_asm_arm",
         "libc_asm_arm64",
+        "libc_asm_riscv64",
         "libc_asm_x86",
         "libc_asm_x86_64",
     ],
@@ -2348,7 +2389,6 @@
         "kernel/uapi/linux/input.h",
         "kernel/uapi/linux/input-event-codes.h",
     ],
-    bazel_module: { bp2build_available: true },
 }
 
 // Generate a syscall name / number mapping. These objects are text files
@@ -2374,8 +2414,6 @@
         "kernel/uapi/asm-arm",
         "kernel/uapi",
     ],
-
-    bazel_module: { bp2build_available: true },
 }
 
 cc_object {
@@ -2385,8 +2423,15 @@
         "kernel/uapi/asm-arm64",
         "kernel/uapi",
     ],
+}
 
-    bazel_module: { bp2build_available: true },
+cc_object {
+    name: "libseccomp_gen_syscall_nrs_riscv64",
+    defaults: ["libseccomp_gen_syscall_nrs_defaults"],
+    local_include_dirs: [
+        "kernel/uapi/asm-riscv",
+        "kernel/uapi",
+    ],
 }
 
 cc_object {
@@ -2398,8 +2443,6 @@
         "kernel/uapi/asm-x86",
         "kernel/uapi",
     ],
-
-    bazel_module: { bp2build_available: true },
 }
 
 cc_object {
@@ -2411,14 +2454,11 @@
         "kernel/uapi/asm-x86",
         "kernel/uapi",
     ],
-
-    bazel_module: { bp2build_available: true },
 }
 
 filegroup {
     name: "all_kernel_uapi_headers",
     srcs: ["kernel/uapi/**/*.h"],
-    bazel_module: { bp2build_available: true },
 }
 
 
@@ -2431,12 +2471,38 @@
 
     srcs: [
         "SYSCALLS.TXT",
-        ":libseccomp_gen_syscall_nrs_arm",
-        ":libseccomp_gen_syscall_nrs_arm64",
-        ":libseccomp_gen_syscall_nrs_x86",
-        ":libseccomp_gen_syscall_nrs_x86_64",
     ],
 
+    arch: {
+        arm: {
+            srcs: [
+                ":libseccomp_gen_syscall_nrs_arm",
+                ":libseccomp_gen_syscall_nrs_arm64",
+            ],
+        },
+        arm64: {
+            srcs: [
+                ":libseccomp_gen_syscall_nrs_arm",
+                ":libseccomp_gen_syscall_nrs_arm64",
+            ],
+        },
+        riscv64: {
+            srcs: [":libseccomp_gen_syscall_nrs_riscv64"],
+        },
+        x86: {
+            srcs: [
+                ":libseccomp_gen_syscall_nrs_x86",
+                ":libseccomp_gen_syscall_nrs_x86_64",
+            ],
+        },
+        x86_64: {
+            srcs: [
+                ":libseccomp_gen_syscall_nrs_x86",
+                ":libseccomp_gen_syscall_nrs_x86_64",
+            ],
+        },
+    },
+
     out: [
         "func_to_syscall_nrs.h",
     ],
@@ -2450,13 +2516,8 @@
     cmd: "grep -v '^int[ \t]*setresgid' $(in) > $(out)",
 }
 
-cc_genrule {
-    name: "libseccomp_policy_app_zygote_sources",
-    recovery_available: true,
-    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=app_zygote $(in)",
-
-    tools: [ "genseccomp" ],
-
+filegroup {
+    name: "seccomp_syscalls_sources_zygote",
     srcs: [
         "SYSCALLS.TXT",
         "SECCOMP_ALLOWLIST_COMMON.TXT",
@@ -2464,27 +2525,11 @@
         "SECCOMP_BLOCKLIST_COMMON.TXT",
         "SECCOMP_PRIORITY.TXT",
         ":generate_app_zygote_blocklist",
-        ":libseccomp_gen_syscall_nrs_arm",
-        ":libseccomp_gen_syscall_nrs_arm64",
-        ":libseccomp_gen_syscall_nrs_x86",
-        ":libseccomp_gen_syscall_nrs_x86_64",
-    ],
-
-    out: [
-        "arm64_app_zygote_policy.cpp",
-        "arm_app_zygote_policy.cpp",
-        "x86_64_app_zygote_policy.cpp",
-        "x86_app_zygote_policy.cpp",
     ],
 }
 
-cc_genrule {
-    name: "libseccomp_policy_app_sources",
-    recovery_available: true,
-    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=app $(in)",
-
-    tools: [ "genseccomp" ],
-
+filegroup {
+    name: "seccomp_syscalls_sources_app",
     srcs: [
         "SYSCALLS.TXT",
         "SECCOMP_ALLOWLIST_COMMON.TXT",
@@ -2492,56 +2537,242 @@
         "SECCOMP_BLOCKLIST_COMMON.TXT",
         "SECCOMP_BLOCKLIST_APP.TXT",
         "SECCOMP_PRIORITY.TXT",
-        ":libseccomp_gen_syscall_nrs_arm",
-        ":libseccomp_gen_syscall_nrs_arm64",
-        ":libseccomp_gen_syscall_nrs_x86",
-        ":libseccomp_gen_syscall_nrs_x86_64",
-    ],
-
-    out: [
-        "arm64_app_policy.cpp",
-        "arm_app_policy.cpp",
-        "x86_64_app_policy.cpp",
-        "x86_app_policy.cpp",
     ],
 }
 
-cc_genrule {
-    name: "libseccomp_policy_system_sources",
-    recovery_available: true,
-    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=system $(in)",
-
-    tools: [ "genseccomp" ],
-
+filegroup {
+    name: "seccomp_syscalls_sources_system",
     srcs: [
         "SYSCALLS.TXT",
         "SECCOMP_ALLOWLIST_COMMON.TXT",
         "SECCOMP_ALLOWLIST_SYSTEM.TXT",
         "SECCOMP_BLOCKLIST_COMMON.TXT",
         "SECCOMP_PRIORITY.TXT",
-        ":libseccomp_gen_syscall_nrs_arm",
-        ":libseccomp_gen_syscall_nrs_arm64",
+    ],
+}
+
+cc_genrule {
+    name: "libseccomp_policy_app_zygote_sources_x86",
+    recovery_available: true,
+    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=app_zygote $(in)",
+    tools: [ "genseccomp" ],
+    srcs: [
+        ":seccomp_syscalls_sources_zygote",
         ":libseccomp_gen_syscall_nrs_x86",
         ":libseccomp_gen_syscall_nrs_x86_64",
     ],
-
     out: [
-        "arm64_system_policy.cpp",
-        "arm_system_policy.cpp",
-        "x86_64_system_policy.cpp",
-        "x86_system_policy.cpp",
+        "x86_app_zygote_policy.cpp",
+        "x86_64_app_zygote_policy.cpp",
     ],
+    enabled: false,
+    arch: {
+        x86: { enabled: true },
+        x86_64: { enabled: true },
+    },
+}
+
+cc_genrule {
+    name: "libseccomp_policy_app_zygote_sources_arm",
+    recovery_available: true,
+    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=app_zygote $(in)",
+    tools: [ "genseccomp" ],
+    srcs: [
+        ":seccomp_syscalls_sources_zygote",
+        ":libseccomp_gen_syscall_nrs_arm",
+        ":libseccomp_gen_syscall_nrs_arm64",
+    ],
+    out: [
+        "arm_app_zygote_policy.cpp",
+        "arm64_app_zygote_policy.cpp",
+    ],
+    enabled: false,
+    arch: {
+        arm: { enabled: true },
+        arm64: { enabled: true },
+    },
+}
+
+cc_genrule {
+    name: "libseccomp_policy_app_zygote_sources_riscv64",
+    recovery_available: true,
+    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=app_zygote $(in)",
+    tools: [ "genseccomp" ],
+    srcs: [
+        ":seccomp_syscalls_sources_zygote",
+        ":libseccomp_gen_syscall_nrs_riscv64",
+    ],
+    out: [
+        "riscv64_app_zygote_policy.cpp",
+    ],
+    enabled: false,
+    arch: {
+        riscv64: { enabled: true },
+    },
+}
+
+cc_genrule {
+    name: "libseccomp_policy_app_sources_x86",
+    recovery_available: true,
+    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=app $(in)",
+    tools: [ "genseccomp" ],
+    srcs: [
+        ":seccomp_syscalls_sources_app",
+        ":libseccomp_gen_syscall_nrs_x86",
+        ":libseccomp_gen_syscall_nrs_x86_64",
+    ],
+    out: [
+        "x86_app_policy.cpp",
+        "x86_64_app_policy.cpp",
+    ],
+    enabled: false,
+    arch: {
+        x86: { enabled: true },
+        x86_64: { enabled: true },
+    },
+}
+
+cc_genrule {
+    name: "libseccomp_policy_app_sources_arm",
+    recovery_available: true,
+    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=app $(in)",
+    tools: [ "genseccomp" ],
+    srcs: [
+        ":seccomp_syscalls_sources_app",
+        ":libseccomp_gen_syscall_nrs_arm",
+        ":libseccomp_gen_syscall_nrs_arm64",
+    ],
+    out: [
+        "arm_app_policy.cpp",
+        "arm64_app_policy.cpp",
+    ],
+    enabled: false,
+    arch: {
+        arm: { enabled: true },
+        arm64: { enabled: true },
+    },
+}
+
+cc_genrule {
+    name: "libseccomp_policy_app_sources_riscv64",
+    recovery_available: true,
+    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=app $(in)",
+    tools: [ "genseccomp" ],
+    srcs: [
+        ":seccomp_syscalls_sources_app",
+        ":libseccomp_gen_syscall_nrs_riscv64",
+    ],
+    out: [
+        "riscv64_app_policy.cpp",
+    ],
+    enabled: false,
+    arch: {
+        riscv64: { enabled: true },
+    },
+}
+
+cc_genrule {
+    name: "libseccomp_policy_system_sources_x86",
+    recovery_available: true,
+    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=system $(in)",
+    tools: [ "genseccomp" ],
+    srcs: [
+        ":seccomp_syscalls_sources_system",
+        ":libseccomp_gen_syscall_nrs_x86",
+        ":libseccomp_gen_syscall_nrs_x86_64",
+    ],
+    out: [
+        "x86_system_policy.cpp",
+        "x86_64_system_policy.cpp",
+    ],
+    enabled: false,
+    arch: {
+        x86: { enabled: true },
+        x86_64: { enabled: true },
+    },
+}
+
+cc_genrule {
+    name: "libseccomp_policy_system_sources_arm",
+    recovery_available: true,
+    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=system $(in)",
+    tools: [ "genseccomp" ],
+    srcs: [
+        ":seccomp_syscalls_sources_system",
+        ":libseccomp_gen_syscall_nrs_arm",
+        ":libseccomp_gen_syscall_nrs_arm64",
+    ],
+    out: [
+        "arm_system_policy.cpp",
+        "arm64_system_policy.cpp",
+    ],
+    enabled: false,
+    arch: {
+        arm: { enabled: true },
+        arm64: { enabled: true },
+    },
+}
+
+cc_genrule {
+    name: "libseccomp_policy_system_sources_riscv64",
+    recovery_available: true,
+    cmd: "$(location genseccomp) --out-dir=$(genDir) --name-modifier=system $(in)",
+    tools: [ "genseccomp" ],
+    srcs: [
+        ":seccomp_syscalls_sources_system",
+        ":libseccomp_gen_syscall_nrs_riscv64",
+    ],
+    out: [
+        "riscv64_system_policy.cpp",
+    ],
+    enabled: false,
+    arch: {
+        riscv64: { enabled: true },
+    },
 }
 
 cc_library {
     name: "libseccomp_policy",
     recovery_available: true,
     generated_headers: ["func_to_syscall_nrs"],
-    generated_sources: [
-        "libseccomp_policy_app_sources",
-        "libseccomp_policy_app_zygote_sources",
-        "libseccomp_policy_system_sources",
-    ],
+
+    arch: {
+        arm: {
+            generated_sources: [
+               "libseccomp_policy_app_sources_arm",
+               "libseccomp_policy_app_zygote_sources_arm",
+               "libseccomp_policy_system_sources_arm",
+            ],
+        },
+        arm64: {
+            generated_sources: [
+               "libseccomp_policy_app_sources_arm",
+               "libseccomp_policy_app_zygote_sources_arm",
+               "libseccomp_policy_system_sources_arm",
+            ],
+        },
+        riscv64: {
+            generated_sources: [
+               "libseccomp_policy_app_sources_riscv64",
+               "libseccomp_policy_app_zygote_sources_riscv64",
+               "libseccomp_policy_system_sources_riscv64",
+            ],
+        },
+        x86: {
+            generated_sources: [
+               "libseccomp_policy_app_sources_x86",
+               "libseccomp_policy_app_zygote_sources_x86",
+               "libseccomp_policy_system_sources_x86",
+            ],
+        },
+        x86_64: {
+            generated_sources: [
+               "libseccomp_policy_app_sources_x86",
+               "libseccomp_policy_app_zygote_sources_x86",
+               "libseccomp_policy_system_sources_x86",
+            ],
+        },
+    },
 
     srcs: [
         "seccomp/seccomp_policy.cpp",
@@ -2712,3 +2943,53 @@
     tools: ["soong_zip"],
     cmd: "includes=($(in)) && $(location soong_zip) -o $(out) -P include/asm -j -D $$(dirname $${includes[0]})",
 }
+
+cc_genrule {
+    name: "bionic_sysroot_crt_objects",
+    visibility: ["//visibility:private"],
+    out: ["bionic_sysroot_crt_objects.zip"],
+    tools: ["soong_zip"],
+    srcs: [
+        ":crtbegin_dynamic",
+        ":crtbegin_so",
+        ":crtbegin_static",
+        ":crtend_android",
+        ":crtend_so",
+    ],
+    cmd: "$(location soong_zip) -o $(out) -j " +
+        "-f $(location :crtbegin_dynamic) " +
+        "-f $(location :crtbegin_so) " +
+        "-f $(location :crtbegin_static) " +
+        "-f $(location :crtend_android) " +
+        "-f $(location :crtend_so)",
+    dist: {
+        targets: ["bionic_sysroot_crt_objects"],
+    },
+    arch: {
+        arm: {
+            dist: {
+                suffix: "_arm",
+            },
+        },
+        arm64: {
+            dist: {
+                suffix: "_arm64",
+            },
+        },
+        riscv64: {
+            dist: {
+                suffix: "_riscv64",
+            },
+        },
+        x86: {
+            dist: {
+                suffix: "_x86",
+            },
+        },
+        x86_64: {
+            dist: {
+                suffix: "_x86_64",
+            },
+        },
+    },
+}
diff --git a/libc/BUILD b/libc/BUILD
index e26c026..1777ae9 100644
--- a/libc/BUILD
+++ b/libc/BUILD
@@ -27,16 +27,16 @@
 load("//build/bazel/rules/apis:cc_api_contribution.bzl", "cc_api_contribution")
 
 cc_api_contribution(
-  name="libc_contributions",
-  library_name="libc",
-  api=":libc.map.txt",
-  hdrs=[
-    "//bionic/libc/kernel/android:libc_kernel_android_uapi_headers",
-    "//bionic/libc/kernel/android:libc_kernel_android_scsi_headers",
-    "//bionic/libc/kernel/uapi:libc_kernel_uapi_headers",
-    "//bionic/libc/kernel/uapi:libc_kernal_uapi_asm_arm_headers", #arm
-    "//bionic/libc/kernel/uapi:libc_kernal_uapi_asm_arm64_headers", #arm64
-    "//bionic/libc/kernel/uapi:libc_kernal_uapi_asm_x86_headers", #x86
-    "//bionic/libc/kernel/uapi:libc_kernal_uapi_asm_x86_64_headers", #x86_64
-  ],
+    name = "libc_contributions",
+    hdrs = [
+        "//bionic/libc/kernel/android:libc_kernel_android_scsi_headers",
+        "//bionic/libc/kernel/android:libc_kernel_android_uapi_headers",
+        "//bionic/libc/kernel/uapi:libc_kernel_uapi_asm_arm64_headers",  #arm64
+        "//bionic/libc/kernel/uapi:libc_kernel_uapi_asm_arm_headers",  #arm
+        "//bionic/libc/kernel/uapi:libc_kernel_uapi_asm_x86_64_headers",  #x86_64
+        "//bionic/libc/kernel/uapi:libc_kernel_uapi_asm_x86_headers",  #x86
+        "//bionic/libc/kernel/uapi:libc_kernel_uapi_headers",
+    ],
+    api = ":libc.map.txt",
+    library_name = "libc",
 )
diff --git a/libc/NOTICE b/libc/NOTICE
index fa3dd2c..51f43f1 100644
--- a/libc/NOTICE
+++ b/libc/NOTICE
@@ -2052,6 +2052,38 @@
 
 Copyright (c) 1990, 1993
    The Regents of the University of California.  All rights reserved.
+
+This code is derived from software contributed to Berkeley by
+Mike Hibler and Chris Torek.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. Neither the name of the University nor the names of its contributors
+   may be used to endorse or promote products derived from this software
+   without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+
+-------------------------------------------------------------------
+
+Copyright (c) 1990, 1993
+   The Regents of the University of California.  All rights reserved.
 (c) UNIX System Laboratories, Inc.
 All or some portions of this file are derived from material licensed
 to the University of California by American Telephone and Telegraph
@@ -4561,6 +4593,34 @@
 
 -------------------------------------------------------------------
 
+Copyright (c) 2017, 2018 Dell EMC
+Copyright (c) 2000, 2001, 2008, 2011, David E. O'Brien
+Copyright (c) 1998 John D. Polstra.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+
+-------------------------------------------------------------------
+
 Copyright (c)1999 Citrus Project,
 All rights reserved.
 
diff --git a/libc/SECCOMP_ALLOWLIST_APP.TXT b/libc/SECCOMP_ALLOWLIST_APP.TXT
index ba40b60..39c6c53 100644
--- a/libc/SECCOMP_ALLOWLIST_APP.TXT
+++ b/libc/SECCOMP_ALLOWLIST_APP.TXT
@@ -56,3 +56,7 @@
 
 # b/62090571
 int mkdir(const char *pathname, mode_t mode)	lp32
+
+# Not used by bionic in U because riscv64 doesn't have it, but still
+# used by legacy apps (http://b/254179267).
+int renameat(int, const char*, int, const char*)  arm,x86,arm64,x86-64
diff --git a/libc/SYSCALLS.TXT b/libc/SYSCALLS.TXT
index fe01ab9..1b9054b 100644
--- a/libc/SYSCALLS.TXT
+++ b/libc/SYSCALLS.TXT
@@ -7,7 +7,7 @@
 # where:
 #       arch_list ::= "all" | arches
 #       arches    ::= arch |  arch "," arches
-#       arch      ::= "arm" | "arm64" | "x86" | "x86_64" | "lp32" | "lp64"
+#       arch      ::= "arm" | "arm64" | "riscv64" | "x86" | "x86_64" | "lp32" | "lp64"
 #
 # Note:
 #      - syscall_name corresponds to the name of the syscall, which may differ from
@@ -352,6 +352,9 @@
 int     __set_tls:__ARM_NR_set_tls(void*)                                 arm
 int     cacheflush:__ARM_NR_cacheflush(long start, long end, long flags)  arm
 
+# riscv64-specific
+int _flush_icache:riscv_flush_icache(void*, void*, unsigned long) riscv64
+
 # x86-specific
 int     __set_thread_area:set_thread_area(void*) x86
 
diff --git a/libc/arch-arm64/bionic/vfork.S b/libc/arch-arm64/bionic/vfork.S
index 9878e8d..9eb82d8 100644
--- a/libc/arch-arm64/bionic/vfork.S
+++ b/libc/arch-arm64/bionic/vfork.S
@@ -29,10 +29,7 @@
 #include <platform/bionic/tls_defines.h>
 #include <private/bionic_asm.h>
 #include <asm/signal.h>
-
-// Must match the defines in linux/sched.h
-#define CLONE_VM 0x00000100
-#define CLONE_VFORK 0x00004000
+#include <linux/sched.h>
 
 ENTRY(vfork)
 __BIONIC_WEAK_ASM_FOR_NATIVE_BRIDGE(vfork)
diff --git a/libc/arch-common/bionic/crtbegin.c b/libc/arch-common/bionic/crtbegin.c
index 9b8ad4e..b87db64 100644
--- a/libc/arch-common/bionic/crtbegin.c
+++ b/libc/arch-common/bionic/crtbegin.c
@@ -56,6 +56,8 @@
 __asm__(PRE
         "xorl %ebp,%ebp; movl %esp,%eax; andl $~0xf,%esp; subl $12,%esp; pushl %eax;"
         "call _start_main" POST);
+#elif defined(__riscv)
+__asm__(PRE "li fp,0; li ra,0; mv a0,sp; tail _start_main" POST);
 #elif defined(__x86_64__)
 __asm__(PRE "xorl %ebp, %ebp; movq %rsp,%rdi; andq $~0xf,%rsp; callq _start_main" POST);
 #else
diff --git a/libc/arch-riscv64/bionic/__bionic_clone.S b/libc/arch-riscv64/bionic/__bionic_clone.S
new file mode 100644
index 0000000..d535095
--- /dev/null
+++ b/libc/arch-riscv64/bionic/__bionic_clone.S
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <private/bionic_asm.h>
+
+// pid_t __bionic_clone(int flags, void* child_stack, pid_t* parent_tid, void* tls, pid_t* child_tid, int (*fn)(void*), void* arg);
+
+ENTRY_PRIVATE(__bionic_clone)
+  # Push 'fn' and 'arg' onto the child stack.
+  addi a1, a1, -16
+  sd a5, 0(a1)
+  sd a6, 8(a1)
+
+  # Make the system call.
+  li a7, __NR_clone
+  ecall
+
+  # Are we the child?
+  beqz a0, .L_bc_child
+
+  # Did the clone(2) fail?
+  bltz a0, .L_bc_failure
+  # Nope, we're the parent, and our work here is done.
+  ret
+
+.L_bc_failure:
+  # Set errno if something went wrong.
+  neg a0, a0
+  j __set_errno_internal
+
+.L_bc_child:
+  # We're in the child now. Set the end of the frame record chain.
+  li fp, 0
+  # Setting ra to 0 will make the unwinder stop at __start_thread.
+  li ra, 0
+  # Call __start_thread with the 'fn' and 'arg' we stored on the child stack.
+  ld a0, 0(sp)
+  ld a1, 8(sp)
+  addi sp, sp, 16
+  j __start_thread
+END(__bionic_clone)
diff --git a/libc/arch-riscv64/bionic/__set_tls.c b/libc/arch-riscv64/bionic/__set_tls.c
new file mode 100644
index 0000000..57383ab
--- /dev/null
+++ b/libc/arch-riscv64/bionic/__set_tls.c
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/cdefs.h>
+
+__LIBC_HIDDEN__ void __set_tls(void* tls) {
+  asm("mv tp, %0" : : "r"(tls));
+}
diff --git a/libc/arch-riscv64/bionic/_exit_with_stack_teardown.S b/libc/arch-riscv64/bionic/_exit_with_stack_teardown.S
new file mode 100644
index 0000000..f7bf58b
--- /dev/null
+++ b/libc/arch-riscv64/bionic/_exit_with_stack_teardown.S
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <private/bionic_asm.h>
+
+// void _exit_with_stack_teardown(void* stackBase, size_t stackSize)
+ENTRY_PRIVATE(_exit_with_stack_teardown)
+  li a7, __NR_munmap
+  ecall
+  // If munmap failed, we ignore the failure and exit anyway.
+
+  li a0, 0
+  li a7, __NR_exit
+  ecall
+  // The exit syscall does not return.
+END(_exit_with_stack_teardown)
diff --git a/libc/arch-riscv64/bionic/setjmp.S b/libc/arch-riscv64/bionic/setjmp.S
new file mode 100644
index 0000000..eea2978
--- /dev/null
+++ b/libc/arch-riscv64/bionic/setjmp.S
@@ -0,0 +1,287 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <private/bionic_asm.h>
+#include <private/bionic_constants.h>
+
+// The internal structure of a jmp_buf is totally private.
+// Current layout (changes from release to release):
+//
+// word   name            description
+// 0      sigflag/cookie  setjmp cookie in top 31 bits, signal mask flag in low bit
+// 1      sigmask         64-bit signal mask
+// 2      ra
+// 3      s0
+// ......
+// 14     s11
+// 15     sp
+// 16     fs0
+// ......
+// 27     fs11
+// 28     checksum
+// _JBLEN: defined in bionic/libc/include/setjmp.h
+
+#define _JB_SIGFLAG   0
+#define _JB_SIGMASK   1 * 8
+#define _JB_RA        2 * 8
+#define _JB_S0        3 * 8
+#define _JB_S1        4 * 8
+#define _JB_S2        5 * 8
+#define _JB_S3        6 * 8
+#define _JB_S4        7 * 8
+#define _JB_S5        8 * 8
+#define _JB_S6        9 * 8
+#define _JB_S7       10 * 8
+#define _JB_S8       11 * 8
+#define _JB_S9       12 * 8
+#define _JB_S10      13 * 8
+#define _JB_S11      14 * 8
+#define _JB_SP       15 * 8
+#define _JB_FS0      16 * 8
+#define _JB_FS1      17 * 8
+#define _JB_FS2      18 * 8
+#define _JB_FS3      19 * 8
+#define _JB_FS4      20 * 8
+#define _JB_FS5      21 * 8
+#define _JB_FS6      22 * 8
+#define _JB_FS7      23 * 8
+#define _JB_FS8      24 * 8
+#define _JB_FS9      25 * 8
+#define _JB_FS10     26 * 8
+#define _JB_FS11     27 * 8
+#define _JB_CHECKSUM 28 * 8
+
+.macro m_mangle_registers reg, sp_reg
+  xor s0, s0, \reg
+  xor s1, s1, \reg
+  xor s2, s2, \reg
+  xor s3, s3, \reg
+  xor s4, s4, \reg
+  xor s5, s5, \reg
+  xor s6, s6, \reg
+  xor s7, s7, \reg
+  xor s8, s8, \reg
+  xor s9, s9, \reg
+  xor s10, s10, \reg
+  xor s11, s11, \reg
+  xor \sp_reg, \sp_reg, \reg
+.endm
+
+.macro m_calculate_checksum dst, src, scratch
+  li \dst, 0
+  .irp i,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27
+    ld \scratch, (\i * 8)(\src)
+    xor \dst, \dst, \scratch
+  .endr
+.endm
+
+.macro m_unmangle_registers reg, sp_reg
+  m_mangle_registers \reg, sp_reg=\sp_reg
+.endm
+
+ENTRY(setjmp)
+__BIONIC_WEAK_ASM_FOR_NATIVE_BRIDGE(setjmp)
+  li a1, 1
+  tail sigsetjmp
+END(setjmp)
+
+ENTRY(_setjmp)
+__BIONIC_WEAK_ASM_FOR_NATIVE_BRIDGE(_setjmp)
+  li a1, 0
+  tail sigsetjmp
+END(_setjmp)
+
+// int sigsetjmp(sigjmp_buf env, int save_signal_mask);
+ENTRY(sigsetjmp)
+__BIONIC_WEAK_ASM_FOR_NATIVE_BRIDGE(sigsetjmp)
+  addi sp, sp, -24
+  sd a0, 0(sp)
+  sd a1, 8(sp)
+  sd ra, 16(sp)
+
+  // Get the cookie and store it along with the signal flag.
+  mv a0, a1
+  call __bionic_setjmp_cookie_get
+  mv a1, a0
+  ld a0, 0(sp)
+  sd a1, _JB_SIGFLAG(a0)
+
+  // Do we need to save the signal mask?
+  andi a1, a1, 1
+  beqz a1, 1f
+
+  // Save current signal mask.
+  // The 'how'/a0 argument is ignored if set is NULL.
+  li a1, 0 // NULL
+  addi a2, a0, _JB_SIGMASK // old_mask.
+  call sigprocmask
+
+1:
+  // Restore original a0/ra.
+  ld a0, 0(sp)
+  ld ra, 16(sp)
+  addi sp, sp, 24
+
+  // Get the cookie.
+  ld a1, _JB_SIGFLAG(a0)
+  andi a1, a1, -2
+
+  // Save core registers.
+  mv a2, sp
+  m_mangle_registers a1, sp_reg=a2
+  sd ra,  _JB_RA(a0)
+  sd s0,  _JB_S0(a0)
+  sd s1,  _JB_S1(a0)
+  sd s2,  _JB_S2(a0)
+  sd s3,  _JB_S3(a0)
+  sd s4,  _JB_S4(a0)
+  sd s5,  _JB_S5(a0)
+  sd s6,  _JB_S6(a0)
+  sd s7,  _JB_S7(a0)
+  sd s8,  _JB_S8(a0)
+  sd s9,  _JB_S9(a0)
+  sd s10, _JB_S10(a0)
+  sd s11, _JB_S11(a0)
+  sd a2,  _JB_SP(a0)
+  m_unmangle_registers a1, sp_reg=a2
+
+  // Save floating point registers.
+  fsd fs0,  _JB_FS0(a0)
+  fsd fs1,  _JB_FS1(a0)
+  fsd fs2,  _JB_FS2(a0)
+  fsd fs3,  _JB_FS3(a0)
+  fsd fs4,  _JB_FS4(a0)
+  fsd fs5,  _JB_FS5(a0)
+  fsd fs6,  _JB_FS6(a0)
+  fsd fs7,  _JB_FS7(a0)
+  fsd fs8,  _JB_FS8(a0)
+  fsd fs9,  _JB_FS9(a0)
+  fsd fs10, _JB_FS10(a0)
+  fsd fs11, _JB_FS11(a0)
+
+  // Calculate the checksum and save it.
+  m_calculate_checksum t0, a0, t1
+  sd t0, _JB_CHECKSUM(a0)
+
+  li a0, 0
+  ret
+END(sigsetjmp)
+
+// void siglongjmp(sigjmp_buf env, int value);
+ENTRY(siglongjmp)
+__BIONIC_WEAK_ASM_FOR_NATIVE_BRIDGE(siglongjmp)
+  // Check the checksum before doing anything.
+  m_calculate_checksum t0, a0, t1
+  ld t1, _JB_CHECKSUM(a0)
+  bne t0, t1, 3f
+
+  // Do we need to restore the signal mask?
+  ld a2, _JB_SIGFLAG(a0)
+  andi a3, a2, 1
+  beqz a3, 1f
+
+  addi sp, sp, -16
+  sd a0, 0(sp)
+  sd ra, 8(sp)
+
+  // Restore the signal mask.
+  mv t0, a1 // Save 'value'.
+
+  mv a2, a0
+  li a0, 2 // SIG_SETMASK
+  addi a1, a2, _JB_SIGMASK // new_mask
+  li a2, 0 // NULL
+  call sigprocmask
+  mv a1, t0 // Restore 'value'.
+
+  // Restore original a0 and ra.
+  ld a0, 0(sp)
+  ld ra, 8(sp)
+  addi sp, sp, 16
+
+  ld a2, _JB_SIGFLAG(a0)
+1:
+  // Restore core registers.
+  andi a2, a2, -2
+  ld ra,  _JB_RA(a0)
+  ld s0,  _JB_S0(a0)
+  ld s1,  _JB_S1(a0)
+  ld s2,  _JB_S2(a0)
+  ld s3,  _JB_S3(a0)
+  ld s4,  _JB_S4(a0)
+  ld s5,  _JB_S5(a0)
+  ld s6,  _JB_S6(a0)
+  ld s7,  _JB_S7(a0)
+  ld s8,  _JB_S8(a0)
+  ld s9,  _JB_S9(a0)
+  ld s10, _JB_S10(a0)
+  ld s11, _JB_S11(a0)
+  ld a3,  _JB_SP(a0)
+  m_unmangle_registers a2, sp_reg=a3
+  mv sp, a3
+
+  addi sp, sp, -24
+  sd   ra, 0(sp)
+  sd   a0, 8(sp)
+  sd   a1, 16(sp)
+  ld   a0, _JB_SIGFLAG(a0)
+  call __bionic_setjmp_cookie_check
+  ld   ra, 0(sp)
+  ld   a0, 8(sp)
+  ld   a1, 16(sp)
+  addi sp, sp, 24
+
+  // Restore floating point registers.
+  fld fs0,  _JB_FS0(a0)
+  fld fs1,  _JB_FS1(a0)
+  fld fs2,  _JB_FS2(a0)
+  fld fs3,  _JB_FS3(a0)
+  fld fs4,  _JB_FS4(a0)
+  fld fs5,  _JB_FS5(a0)
+  fld fs6,  _JB_FS6(a0)
+  fld fs7,  _JB_FS7(a0)
+  fld fs8,  _JB_FS8(a0)
+  fld fs9,  _JB_FS9(a0)
+  fld fs10, _JB_FS10(a0)
+  fld fs11, _JB_FS11(a0)
+
+  // Set return value.
+  beqz a1, 2f
+  li a0, 1
+2:
+  mv a0, a1
+  ret
+
+3:
+  call __bionic_setjmp_checksum_mismatch
+END(siglongjmp)
+
+ALIAS_SYMBOL(longjmp, siglongjmp)
+__BIONIC_WEAK_ASM_FOR_NATIVE_BRIDGE(longjmp)
+ALIAS_SYMBOL(_longjmp, siglongjmp)
+__BIONIC_WEAK_ASM_FOR_NATIVE_BRIDGE(_longjmp)
diff --git a/libc/arch-riscv64/bionic/syscall.S b/libc/arch-riscv64/bionic/syscall.S
new file mode 100644
index 0000000..7b9d3ca
--- /dev/null
+++ b/libc/arch-riscv64/bionic/syscall.S
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <private/bionic_asm.h>
+
+ENTRY(syscall)
+  // Move the syscall number up.
+  mv a7, a0
+
+  // Shuffle the arguments down.
+  mv a0, a1
+  mv a1, a2
+  mv a2, a3
+  mv a3, a4
+  mv a4, a5
+  mv a5, a6
+
+  ecall
+
+  // Did it fail?
+  li a7, -MAX_ERRNO
+  bgtu a0, a7, 1f
+
+  ret
+1:
+  neg a0, a0
+  j __set_errno_internal
+END(syscall)
diff --git a/libc/arch-riscv64/bionic/vfork.S b/libc/arch-riscv64/bionic/vfork.S
new file mode 100644
index 0000000..0eff9e9
--- /dev/null
+++ b/libc/arch-riscv64/bionic/vfork.S
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <platform/bionic/tls_defines.h>
+#include <private/bionic_asm.h>
+#include <asm/signal.h>
+#include <linux/sched.h>
+
+ENTRY(vfork)
+  // t0 = __get_tls()[TLS_SLOT_THREAD_ID]
+  mv      t0, tp
+  ld      t0, TLS_SLOT_THREAD_ID * 8(t0)
+
+  // Set cached_pid_ to 0, vforked_ to 1, and stash the previous value.
+  li      t1, 0x80000000
+  lw      t2, 20(t0)
+  sw      t1, 20(t0)
+
+  li      a0, (CLONE_VM | CLONE_VFORK | SIGCHLD)
+  li      a1, 0 //uses a duplicate of the parent's stack
+  li      a2, 0
+  li      a3, 0
+  li      a4, 0
+
+  li      a7, __NR_clone
+  ecall
+
+  // if (rc == 0) we're the child, and finished...
+  beqz    a0, .L_success
+
+  // else if (rc != 0): reset cached_pid_ and vforked_...
+  sw      t2, 20(t0)
+  // ...and work out whether we succeeded or failed.
+  bltz    a0, .L_failure
+.L_success:
+  ret
+
+.L_failure:
+  neg     a0, a0
+  j       __set_errno_internal
+END(vfork)
diff --git a/libc/arch-riscv64/string/memset_chk.c b/libc/arch-riscv64/string/memset_chk.c
new file mode 100644
index 0000000..bdd15a5
--- /dev/null
+++ b/libc/arch-riscv64/string/memset_chk.c
@@ -0,0 +1,9 @@
+#include <stdint.h>
+
+extern void* memset(void*, int, size_t);
+extern void* __memset_chk_fail(void*, int, size_t, size_t);
+
+void* __memset_chk(void* dst, int c, size_t n, size_t dst_len) {
+  if (dst_len < n) __memset_chk_fail(dst, c, n, dst_len);
+  return memset(dst, c, n);
+}
diff --git a/libc/bionic/android_profiling_dynamic.cpp b/libc/bionic/android_profiling_dynamic.cpp
index 3460a6d..8c9127e 100644
--- a/libc/bionic/android_profiling_dynamic.cpp
+++ b/libc/bionic/android_profiling_dynamic.cpp
@@ -204,12 +204,14 @@
   auto ret = -ENOSYS;
   ucontext_t* ctx = reinterpret_cast<ucontext_t*>(void_context);
 
-#if defined(__arm__)
+#if defined(__aarch64__)
+  ctx->uc_mcontext.regs[0] = ret;
+#elif defined(__arm__)
   ctx->uc_mcontext.arm_r0 = ret;
-#elif defined(__aarch64__)
-  ctx->uc_mcontext.regs[0] = ret;  // x0
 #elif defined(__i386__)
   ctx->uc_mcontext.gregs[REG_EAX] = ret;
+#elif defined(__riscv)
+  ctx->uc_mcontext.__gregs[REG_A0] = ret;
 #elif defined(__x86_64__)
   ctx->uc_mcontext.gregs[REG_RAX] = ret;
 #else
diff --git a/libc/bionic/bionic_elf_tls.cpp b/libc/bionic/bionic_elf_tls.cpp
index d5fb05a..79893e3 100644
--- a/libc/bionic/bionic_elf_tls.cpp
+++ b/libc/bionic/bionic_elf_tls.cpp
@@ -137,6 +137,15 @@
   offset_bionic_tcb_ = reserve(sizeof(bionic_tcb), max_align);
   return offset_bionic_tcb_ - exe_size;
 
+#elif defined(__riscv)
+
+  // First reserve enough space for the TCB before the executable segment.
+  offset_bionic_tcb_ = reserve(sizeof(bionic_tcb), 1);
+
+  // Then reserve the segment itself.
+  const size_t exe_size = round_up_with_overflow_check(exe_segment->size, exe_segment->alignment);
+  return reserve(exe_size, 1);
+
 #else
 #error "Unrecognized architecture"
 #endif
@@ -312,7 +321,7 @@
     }
   }
 
-  return static_cast<char*>(mod_ptr) + ti->offset;
+  return static_cast<char*>(mod_ptr) + ti->offset + TLS_DTV_OFFSET;
 }
 
 // Returns the address of a thread's TLS memory given a module ID and an offset
@@ -332,7 +341,7 @@
   if (__predict_true(generation == dtv->generation)) {
     void* mod_ptr = dtv->modules[__tls_module_id_to_idx(ti->module_id)];
     if (__predict_true(mod_ptr != nullptr)) {
-      return static_cast<char*>(mod_ptr) + ti->offset;
+      return static_cast<char*>(mod_ptr) + ti->offset + TLS_DTV_OFFSET;
     }
   }
 
diff --git a/libc/include/bits/elf_arm.h b/libc/include/bits/elf_arm.h
deleted file mode 100644
index 08fe1d5..0000000
--- a/libc/include/bits/elf_arm.h
+++ /dev/null
@@ -1,131 +0,0 @@
-/*	$NetBSD: elf_machdep.h,v 1.17 2014/02/25 19:20:09 matt Exp $	*/
-
-#ifndef _ARM_ELF_MACHDEP_H_
-#define _ARM_ELF_MACHDEP_H_
-
-/* Android-added. */
-#define R_ARM_IRELATIVE		160
-
-/* Processor specific flags for the ELF header e_flags field.  */
-#define EF_ARM_RELEXEC		0x00000001
-#define EF_ARM_HASENTRY		0x00000002
-#define EF_ARM_INTERWORK	0x00000004 /* GNU binutils 000413 */
-#define EF_ARM_SYMSARESORTED	0x00000004 /* ARM ELF A08 */
-#define EF_ARM_APCS_26		0x00000008 /* GNU binutils 000413 */
-#define EF_ARM_DYNSYMSUSESEGIDX	0x00000008 /* ARM ELF B01 */
-#define EF_ARM_APCS_FLOAT	0x00000010 /* GNU binutils 000413 */
-#define EF_ARM_MAPSYMSFIRST	0x00000010 /* ARM ELF B01 */
-#define EF_ARM_PIC		0x00000020
-#define EF_ARM_ALIGN8		0x00000040 /* 8-bit structure alignment.  */
-#define EF_ARM_NEW_ABI		0x00000080
-#define EF_ARM_OLD_ABI		0x00000100
-#define EF_ARM_SOFT_FLOAT	0x00000200
-#define EF_ARM_BE8		0x00800000
-#define EF_ARM_EABIMASK		0xff000000
-#define	EF_ARM_EABI_VER1	0x01000000
-#define	EF_ARM_EABI_VER2	0x02000000
-#define	EF_ARM_EABI_VER3	0x03000000
-#define	EF_ARM_EABI_VER4	0x04000000
-#define	EF_ARM_EABI_VER5	0x05000000
-
-/* Processor specific relocation types */
-
-#define R_ARM_NONE		0
-#define R_ARM_PC24		1
-#define R_ARM_ABS32		2
-#define R_ARM_REL32		3
-#define R_ARM_PC13		4
-#define R_ARM_ABS16		5
-#define R_ARM_ABS12		6
-#define R_ARM_THM_ABS5		7
-#define R_ARM_ABS8		8
-#define R_ARM_SBREL32		9
-#define R_ARM_THM_PC22		10
-#define R_ARM_THM_PC8		11
-#define R_ARM_AMP_VCALL9	12
-#define R_ARM_SWI24		13	/* obsolete static relocation */
-#define R_ARM_TLS_DESC		13	/* dynamic relocation */
-#define R_ARM_THM_SWI8		14
-#define R_ARM_XPC25		15
-#define R_ARM_THM_XPC22		16
-
-/* TLS relocations */
-#define R_ARM_TLS_DTPMOD32	17	/* ID of module containing symbol */
-#define R_ARM_TLS_DTPOFF32	18	/* Offset in TLS block */
-#define R_ARM_TLS_TPOFF32	19	/* Offset in static TLS block */
-
-/* 20-31 are reserved for ARM Linux. */
-#define R_ARM_COPY		20
-#define R_ARM_GLOB_DAT		21
-#define	R_ARM_JUMP_SLOT		22
-#define R_ARM_RELATIVE		23
-#define	R_ARM_GOTOFF		24
-#define R_ARM_GOTPC		25
-#define R_ARM_GOT32		26
-#define R_ARM_PLT32		27
-#define R_ARM_CALL		28
-#define R_ARM_JUMP24		29
-#define R_ARM_THM_JUMP24	30
-#define R_ARM_BASE_ABS		31
-#define R_ARM_ALU_PCREL_7_0	32
-#define R_ARM_ALU_PCREL_15_8	33
-#define R_ARM_ALU_PCREL_23_15	34
-#define R_ARM_ALU_SBREL_11_0	35
-#define R_ARM_ALU_SBREL_19_12	36
-#define R_ARM_ALU_SBREL_27_20	37	// depcreated
-#define R_ARM_TARGET1		38
-#define R_ARM_SBREL31		39	// deprecated
-#define R_ARM_V4BX		40
-#define R_ARM_TARGET2		41
-#define R_ARM_PREL31		42
-#define R_ARM_MOVW_ABS_NC	43
-#define R_ARM_MOVT_ABS		44
-#define R_ARM_MOVW_PREL_NC	45
-#define R_ARM_MOVT_PREL		46
-#define R_ARM_THM_MOVW_ABS_NC	47
-#define R_ARM_THM_MOVT_ABS	48
-#define R_ARM_THM_MOVW_PREL_NC	49
-#define R_ARM_THM_MOVT_PREL	50
-
-/* 96-111 are reserved to G++. */
-#define R_ARM_GNU_VTENTRY	100
-#define R_ARM_GNU_VTINHERIT	101
-#define R_ARM_THM_PC11		102
-#define R_ARM_THM_PC9		103
-
-/* More TLS relocations */
-#define R_ARM_TLS_GD32		104	/* PC-rel 32 bit for global dynamic */
-#define R_ARM_TLS_LDM32		105	/* PC-rel 32 bit for local dynamic */
-#define R_ARM_TLS_LDO32		106	/* 32 bit offset relative to TLS */
-#define R_ARM_TLS_IE32		107	/* PC-rel 32 bit for GOT entry of */
-#define R_ARM_TLS_LE32		108
-#define R_ARM_TLS_LDO12		109
-#define R_ARM_TLS_LE12		110
-#define R_ARM_TLS_IE12GP	111
-
-/* 112-127 are reserved for private experiments. */
-
-#define R_ARM_RXPC25		249
-#define R_ARM_RSBREL32		250
-#define R_ARM_THM_RPC22		251
-#define R_ARM_RREL32		252
-#define R_ARM_RABS32		253
-#define R_ARM_RPC24		254
-#define R_ARM_RBASE		255
-
-/* Processor specific program header flags */
-#define PF_ARM_SB		0x10000000
-#define PF_ARM_PI		0x20000000
-#define PF_ARM_ENTRY		0x80000000
-
-/* Processor specific program header types */
-#define PT_ARM_EXIDX		(PT_LOPROC + 1)
-
-/* Processor specific section header flags */
-#define SHF_ENTRYSECT		0x10000000
-#define SHF_COMDEF		0x80000000
-
-/* Processor specific symbol types */
-#define STT_ARM_TFUNC		STT_LOPROC
-
-#endif /* _ARM_ELF_MACHDEP_H_ */
diff --git a/libc/include/bits/elf_arm64.h b/libc/include/bits/elf_arm64.h
deleted file mode 100644
index 9330d7b..0000000
--- a/libc/include/bits/elf_arm64.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef _AARCH64_ELF_MACHDEP_H_
-#define _AARCH64_ELF_MACHDEP_H_
-
-/* Null relocations */
-#define R_ARM_NONE                      0
-#define R_AARCH64_NONE                  256
-
-/* Static Data relocations */
-#define R_AARCH64_ABS64                 257
-#define R_AARCH64_ABS32                 258
-#define R_AARCH64_ABS16                 259
-#define R_AARCH64_PREL64                260
-#define R_AARCH64_PREL32                261
-#define R_AARCH64_PREL16                262
-
-#define R_AARCH64_MOVW_UABS_G0          263
-#define R_AARCH64_MOVW_UABS_G0_NC       264
-#define R_AARCH64_MOVW_UABS_G1          265
-#define R_AARCH64_MOVW_UABS_G1_NC       266
-#define R_AARCH64_MOVW_UABS_G2          267
-#define R_AARCH64_MOVW_UABS_G2_NC       268
-#define R_AARCH64_MOVW_UABS_G3          269
-#define R_AARCH64_MOVW_SABS_G0          270
-#define R_AARCH64_MOVW_SABS_G1          271
-#define R_AARCH64_MOVW_SABS_G2          272
-
-/* PC-relative addresses */
-#define R_AARCH64_LD_PREL_LO19          273
-#define R_AARCH64_ADR_PREL_LO21         274
-#define R_AARCH64_ADR_PREL_PG_HI21      275
-#define R_AARCH64_ADR_PREL_PG_HI21_NC   276
-#define R_AARCH64_ADD_ABS_LO12_NC       277
-#define R_AARCH64_LDST8_ABS_LO12_NC     278
-
-/* Control-flow relocations */
-#define R_AARCH64_TSTBR14               279
-#define R_AARCH64_CONDBR19              280
-#define R_AARCH64_JUMP26                282
-#define R_AARCH64_CALL26                283
-#define R_AARCH64_LDST16_ABS_LO12_NC    284
-#define R_AARCH64_LDST32_ABS_LO12_NC    285
-#define R_AARCH64_LDST64_ABS_LO12_NC    286
-#define R_AARCH64_LDST128_ABS_LO12_NC   299
-
-#define R_AARCH64_MOVW_PREL_G0          287
-#define R_AARCH64_MOVW_PREL_G0_NC       288
-#define R_AARCH64_MOVW_PREL_G1          289
-#define R_AARCH64_MOVW_PREL_G1_NC       290
-#define R_AARCH64_MOVW_PREL_G2          291
-#define R_AARCH64_MOVW_PREL_G2_NC       292
-#define R_AARCH64_MOVW_PREL_G3          293
-
-/* Dynamic relocations */
-#define R_AARCH64_COPY                  1024
-#define R_AARCH64_GLOB_DAT              1025    /* Create GOT entry.  */
-#define R_AARCH64_JUMP_SLOT             1026    /* Create PLT entry.  */
-#define R_AARCH64_RELATIVE              1027    /* Adjust by program base.  */
-#define R_AARCH64_TLS_DTPMOD            1028    /* Module index. */
-#define R_AARCH64_TLS_DTPREL            1029    /* Module-relative offset. */
-#define R_AARCH64_TLS_TPREL             1030    /* TP-relative offset. */
-#define R_AARCH64_TLSDESC               1031    /* 16-byte descriptor: resolver func + arg. */
-#define R_AARCH64_IRELATIVE             1032
-
-/* Dynamic array tags */
-#define DT_AARCH64_BTI_PLT              0x70000001
-#define DT_AARCH64_PAC_PLT              0x70000003
-#define DT_AARCH64_VARIANT_PCS          0x70000005
-
-#endif /* _AARCH64_ELF_MACHDEP_H_ */
diff --git a/libc/include/bits/elf_common.h b/libc/include/bits/elf_common.h
new file mode 100644
index 0000000..ea833f4
--- /dev/null
+++ b/libc/include/bits/elf_common.h
@@ -0,0 +1,1430 @@
+/*-
+ * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
+ *
+ * Copyright (c) 2017, 2018 Dell EMC
+ * Copyright (c) 2000, 2001, 2008, 2011, David E. O'Brien
+ * Copyright (c) 1998 John D. Polstra.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD$
+ */
+
+#ifndef _SYS_ELF_COMMON_H_
+#define	_SYS_ELF_COMMON_H_ 1
+
+/*
+ * ELF definitions that are independent of architecture or word size.
+ */
+
+/*
+ * Option kinds.
+ */
+#define	ODK_NULL	0	/* undefined */
+#define	ODK_REGINFO	1	/* register usage info */
+#define	ODK_EXCEPTIONS	2	/* exception processing info */
+#define	ODK_PAD		3	/* section padding */
+#define	ODK_HWPATCH	4	/* hardware patch applied */
+#define	ODK_FILL	5	/* fill value used by the linker */
+#define	ODK_TAGS	6	/* reserved space for tools */
+#define	ODK_HWAND	7	/* hardware AND patch applied */
+#define	ODK_HWOR	8	/* hardware OR patch applied */
+#define	ODK_GP_GROUP	9	/* GP group for text/data sections */
+#define	ODK_IDENT	10	/* ID information */
+#define	ODK_PAGESIZE	11	/* page size information */
+
+/*
+ * ODK_EXCEPTIONS info field masks.
+ */
+#define	OEX_FPU_MIN	0x0000001f	/* min FPU exception required */
+#define	OEX_FPU_MAX	0x00001f00	/* max FPU exception allowed */
+#define	OEX_PAGE0	0x00010000	/* page zero must be mapped */
+#define	OEX_SMM		0x00020000	/* run in sequential memory mode */
+#define	OEX_PRECISEFP	0x00040000	/* run in precise FP exception mode */
+#define	OEX_DISMISS	0x00080000	/* dismiss invalid address traps */
+
+/*
+ * ODK_PAD info field masks.
+ */
+#define	OPAD_PREFIX	0x0001
+#define	OPAD_POSTFIX	0x0002
+#define	OPAD_SYMBOL	0x0004
+
+/*
+ * ODK_HWPATCH info field masks.
+ */
+#define	OHW_R4KEOP	0x00000001	/* patch for R4000 branch at end-of-page bug */
+#define	OHW_R8KPFETCH	0x00000002	/* R8000 prefetch bug may occur */
+#define	OHW_R5KEOP	0x00000004	/* patch for R5000 branch at end-of-page bug */
+#define	OHW_R5KCVTL	0x00000008	/* R5000 cvt.[ds].l bug: clean == 1 */
+#define	OHW_R10KLDL	0x00000010UL	/* need patch for R10000 misaligned load */
+
+/*
+ * ODK_HWAND/ODK_HWOR info field and hwp_flags[12] masks.
+ */
+#define	OHWA0_R4KEOP_CHECKED	0x00000001	/* object checked for R4000 end-of-page bug */
+#define	OHWA0_R4KEOP_CLEAN	0x00000002	/* object verified clean for R4000 end-of-page bug */
+#define	OHWO0_FIXADE		0x00000001	/* object requires call to fixade */
+
+/*
+ * ODK_IDENT/ODK_GP_GROUP info field masks.
+ */
+#define	OGP_GROUP	0x0000ffff	/* GP group number */
+#define	OGP_SELF	0x00010000	/* GP group is self-contained */
+
+/* Indexes into the e_ident array.  Keep synced with
+   http://www.sco.com/developers/gabi/latest/ch4.eheader.html */
+#define	EI_MAG0		0	/* Magic number, byte 0. */
+#define	EI_MAG1		1	/* Magic number, byte 1. */
+#define	EI_MAG2		2	/* Magic number, byte 2. */
+#define	EI_MAG3		3	/* Magic number, byte 3. */
+#define	EI_CLASS	4	/* Class of machine. */
+#define	EI_DATA		5	/* Data format. */
+#define	EI_VERSION	6	/* ELF format version. */
+#define	EI_OSABI	7	/* Operating system / ABI identification */
+#define	EI_ABIVERSION	8	/* ABI version */
+#define	OLD_EI_BRAND	8	/* Start of architecture identification. */
+#define	EI_PAD		9	/* Start of padding (per SVR4 ABI). */
+#define	EI_NIDENT	16	/* Size of e_ident array. */
+
+/* Values for the magic number bytes. */
+#define	ELFMAG0		0x7f
+#define	ELFMAG1		'E'
+#define	ELFMAG2		'L'
+#define	ELFMAG3		'F'
+#define	ELFMAG		"\177ELF"	/* magic string */
+#define	SELFMAG		4		/* magic string size */
+
+/* Values for e_ident[EI_VERSION] and e_version. */
+#define	EV_NONE		0
+#define	EV_CURRENT	1
+
+/* Values for e_ident[EI_CLASS]. */
+#define	ELFCLASSNONE	0	/* Unknown class. */
+#define	ELFCLASS32	1	/* 32-bit architecture. */
+#define	ELFCLASS64	2	/* 64-bit architecture. */
+
+/* Values for e_ident[EI_DATA]. */
+#define	ELFDATANONE	0	/* Unknown data format. */
+#define	ELFDATA2LSB	1	/* 2's complement little-endian. */
+#define	ELFDATA2MSB	2	/* 2's complement big-endian. */
+
+/* Values for e_ident[EI_OSABI]. */
+#define	ELFOSABI_NONE		0	/* UNIX System V ABI */
+#define	ELFOSABI_HPUX		1	/* HP-UX operating system */
+#define	ELFOSABI_NETBSD		2	/* NetBSD */
+#define	ELFOSABI_LINUX		3	/* GNU/Linux */
+#define	ELFOSABI_HURD		4	/* GNU/Hurd */
+#define	ELFOSABI_86OPEN		5	/* 86Open common IA32 ABI */
+#define	ELFOSABI_SOLARIS	6	/* Solaris */
+#define	ELFOSABI_AIX		7	/* AIX */
+#define	ELFOSABI_IRIX		8	/* IRIX */
+#define	ELFOSABI_FREEBSD	9	/* FreeBSD */
+#define	ELFOSABI_TRU64		10	/* TRU64 UNIX */
+#define	ELFOSABI_MODESTO	11	/* Novell Modesto */
+#define	ELFOSABI_OPENBSD	12	/* OpenBSD */
+#define	ELFOSABI_OPENVMS	13	/* Open VMS */
+#define	ELFOSABI_NSK		14	/* HP Non-Stop Kernel */
+#define	ELFOSABI_AROS		15	/* Amiga Research OS */
+#define	ELFOSABI_FENIXOS	16	/* FenixOS */
+#define	ELFOSABI_CLOUDABI	17	/* Nuxi CloudABI */
+#define	ELFOSABI_OPENVOS	18	/* Stratus Technologies OpenVOS */
+#define	ELFOSABI_ARM_AEABI	64	/* ARM EABI */
+#define	ELFOSABI_ARM		97	/* ARM */
+#define	ELFOSABI_STANDALONE	255	/* Standalone (embedded) application */
+
+#define	ELFOSABI_MONTEREY	ELFOSABI_AIX	/* Monterey */
+
+/* e_ident */
+#define	IS_ELF(ehdr)	((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \
+			 (ehdr).e_ident[EI_MAG1] == ELFMAG1 && \
+			 (ehdr).e_ident[EI_MAG2] == ELFMAG2 && \
+			 (ehdr).e_ident[EI_MAG3] == ELFMAG3)
+
+/* Values for e_type. */
+#define	ET_NONE		0	/* Unknown type. */
+#define	ET_REL		1	/* Relocatable. */
+#define	ET_EXEC		2	/* Executable. */
+#define	ET_DYN		3	/* Shared object. */
+#define	ET_CORE		4	/* Core file. */
+#define	ET_LOOS		0xfe00	/* First operating system specific. */
+#define	ET_HIOS		0xfeff	/* Last operating system-specific. */
+#define	ET_LOPROC	0xff00	/* First processor-specific. */
+#define	ET_HIPROC	0xffff	/* Last processor-specific. */
+
+/* Values for e_machine. */
+#define	EM_NONE		0	/* Unknown machine. */
+#define	EM_M32		1	/* AT&T WE32100. */
+#define	EM_SPARC	2	/* Sun SPARC. */
+#define	EM_386		3	/* Intel i386. */
+#define	EM_68K		4	/* Motorola 68000. */
+#define	EM_88K		5	/* Motorola 88000. */
+#define	EM_IAMCU	6	/* Intel MCU. */
+#define	EM_860		7	/* Intel i860. */
+#define	EM_MIPS		8	/* MIPS R3000 Big-Endian only. */
+#define	EM_S370		9	/* IBM System/370. */
+#define	EM_MIPS_RS3_LE	10	/* MIPS R3000 Little-Endian. */
+#define	EM_PARISC	15	/* HP PA-RISC. */
+#define	EM_VPP500	17	/* Fujitsu VPP500. */
+#define	EM_SPARC32PLUS	18	/* SPARC v8plus. */
+#define	EM_960		19	/* Intel 80960. */
+#define	EM_PPC		20	/* PowerPC 32-bit. */
+#define	EM_PPC64	21	/* PowerPC 64-bit. */
+#define	EM_S390		22	/* IBM System/390. */
+#define	EM_V800		36	/* NEC V800. */
+#define	EM_FR20		37	/* Fujitsu FR20. */
+#define	EM_RH32		38	/* TRW RH-32. */
+#define	EM_RCE		39	/* Motorola RCE. */
+#define	EM_ARM		40	/* ARM. */
+#define	EM_SH		42	/* Hitachi SH. */
+#define	EM_SPARCV9	43	/* SPARC v9 64-bit. */
+#define	EM_TRICORE	44	/* Siemens TriCore embedded processor. */
+#define	EM_ARC		45	/* Argonaut RISC Core. */
+#define	EM_H8_300	46	/* Hitachi H8/300. */
+#define	EM_H8_300H	47	/* Hitachi H8/300H. */
+#define	EM_H8S		48	/* Hitachi H8S. */
+#define	EM_H8_500	49	/* Hitachi H8/500. */
+#define	EM_IA_64	50	/* Intel IA-64 Processor. */
+#define	EM_MIPS_X	51	/* Stanford MIPS-X. */
+#define	EM_COLDFIRE	52	/* Motorola ColdFire. */
+#define	EM_68HC12	53	/* Motorola M68HC12. */
+#define	EM_MMA		54	/* Fujitsu MMA. */
+#define	EM_PCP		55	/* Siemens PCP. */
+#define	EM_NCPU		56	/* Sony nCPU. */
+#define	EM_NDR1		57	/* Denso NDR1 microprocessor. */
+#define	EM_STARCORE	58	/* Motorola Star*Core processor. */
+#define	EM_ME16		59	/* Toyota ME16 processor. */
+#define	EM_ST100	60	/* STMicroelectronics ST100 processor. */
+#define	EM_TINYJ	61	/* Advanced Logic Corp. TinyJ processor. */
+#define	EM_X86_64	62	/* Advanced Micro Devices x86-64 */
+#define	EM_AMD64	EM_X86_64	/* Advanced Micro Devices x86-64 (compat) */
+#define	EM_PDSP		63	/* Sony DSP Processor. */
+#define	EM_FX66		66	/* Siemens FX66 microcontroller. */
+#define	EM_ST9PLUS	67	/* STMicroelectronics ST9+ 8/16
+				   microcontroller. */
+#define	EM_ST7		68	/* STmicroelectronics ST7 8-bit
+				   microcontroller. */
+#define	EM_68HC16	69	/* Motorola MC68HC16 microcontroller. */
+#define	EM_68HC11	70	/* Motorola MC68HC11 microcontroller. */
+#define	EM_68HC08	71	/* Motorola MC68HC08 microcontroller. */
+#define	EM_68HC05	72	/* Motorola MC68HC05 microcontroller. */
+#define	EM_SVX		73	/* Silicon Graphics SVx. */
+#define	EM_ST19		74	/* STMicroelectronics ST19 8-bit mc. */
+#define	EM_VAX		75	/* Digital VAX. */
+#define	EM_CRIS		76	/* Axis Communications 32-bit embedded
+				   processor. */
+#define	EM_JAVELIN	77	/* Infineon Technologies 32-bit embedded
+				   processor. */
+#define	EM_FIREPATH	78	/* Element 14 64-bit DSP Processor. */
+#define	EM_ZSP		79	/* LSI Logic 16-bit DSP Processor. */
+#define	EM_MMIX		80	/* Donald Knuth's educational 64-bit proc. */
+#define	EM_HUANY	81	/* Harvard University machine-independent
+				   object files. */
+#define	EM_PRISM	82	/* SiTera Prism. */
+#define	EM_AVR		83	/* Atmel AVR 8-bit microcontroller. */
+#define	EM_FR30		84	/* Fujitsu FR30. */
+#define	EM_D10V		85	/* Mitsubishi D10V. */
+#define	EM_D30V		86	/* Mitsubishi D30V. */
+#define	EM_V850		87	/* NEC v850. */
+#define	EM_M32R		88	/* Mitsubishi M32R. */
+#define	EM_MN10300	89	/* Matsushita MN10300. */
+#define	EM_MN10200	90	/* Matsushita MN10200. */
+#define	EM_PJ		91	/* picoJava. */
+#define	EM_OPENRISC	92	/* OpenRISC 32-bit embedded processor. */
+#define	EM_ARC_A5	93	/* ARC Cores Tangent-A5. */
+#define	EM_XTENSA	94	/* Tensilica Xtensa Architecture. */
+#define	EM_VIDEOCORE	95	/* Alphamosaic VideoCore processor. */
+#define	EM_TMM_GPP	96	/* Thompson Multimedia General Purpose
+				   Processor. */
+#define	EM_NS32K	97	/* National Semiconductor 32000 series. */
+#define	EM_TPC		98	/* Tenor Network TPC processor. */
+#define	EM_SNP1K	99	/* Trebia SNP 1000 processor. */
+#define	EM_ST200	100	/* STMicroelectronics ST200 microcontroller. */
+#define	EM_IP2K		101	/* Ubicom IP2xxx microcontroller family. */
+#define	EM_MAX		102	/* MAX Processor. */
+#define	EM_CR		103	/* National Semiconductor CompactRISC
+				   microprocessor. */
+#define	EM_F2MC16	104	/* Fujitsu F2MC16. */
+#define	EM_MSP430	105	/* Texas Instruments embedded microcontroller
+				   msp430. */
+#define	EM_BLACKFIN	106	/* Analog Devices Blackfin (DSP) processor. */
+#define	EM_SE_C33	107	/* S1C33 Family of Seiko Epson processors. */
+#define	EM_SEP		108	/* Sharp embedded microprocessor. */
+#define	EM_ARCA		109	/* Arca RISC Microprocessor. */
+#define	EM_UNICORE	110	/* Microprocessor series from PKU-Unity Ltd.
+				   and MPRC of Peking University */
+#define	EM_AARCH64	183	/* AArch64 (64-bit ARM) */
+#define	EM_RISCV	243	/* RISC-V */
+
+/* Non-standard or deprecated. */
+#define	EM_486		6	/* Intel i486. */
+#define	EM_MIPS_RS4_BE	10	/* MIPS R4000 Big-Endian */
+#define	EM_ALPHA_STD	41	/* Digital Alpha (standard value). */
+#define	EM_ALPHA	0x9026	/* Alpha (written in the absence of an ABI) */
+
+/**
+ * e_flags
+ */
+#define	EF_ARM_RELEXEC	0x1
+#define	EF_ARM_HASENTRY	0x2
+#define	EF_ARM_SYMSARESORTED	0x4
+#define	EF_ARM_DYNSYMSUSESEGIDX	0x8
+#define	EF_ARM_MAPSYMSFIRST	0x10
+#define	EF_ARM_LE8		0x00400000
+#define	EF_ARM_BE8		0x00800000
+#define	EF_ARM_EABIMASK		0xFF000000
+#define	EF_ARM_EABI_UNKNOWN	0x00000000
+#define	EF_ARM_EABI_VER1	0x01000000
+#define	EF_ARM_EABI_VER2	0x02000000
+#define	EF_ARM_EABI_VER3	0x03000000
+#define	EF_ARM_EABI_VER4	0x04000000
+#define	EF_ARM_EABI_VER5	0x05000000
+#define	EF_ARM_INTERWORK	0x00000004
+#define	EF_ARM_APCS_26		0x00000008
+#define	EF_ARM_APCS_FLOAT	0x00000010
+#define	EF_ARM_PIC		0x00000020
+#define	EF_ARM_ALIGN8		0x00000040
+#define	EF_ARM_NEW_ABI		0x00000080
+#define	EF_ARM_OLD_ABI		0x00000100
+#define	EF_ARM_ABI_FLOAT_SOFT	0x00000200
+#define	EF_ARM_SOFT_FLOAT	EF_ARM_ABI_FLOAT_SOFT /* Pre-V5 ABI name */
+#define	EF_ARM_ABI_FLOAT_HARD	0x00000400
+#define	EF_ARM_VFP_FLOAT	EF_ARM_ABI_FLOAT_HARD /* Pre-V5 ABI name */
+#define	EF_ARM_MAVERICK_FLOAT	0x00000800
+
+#define	EF_MIPS_NOREORDER	0x00000001
+#define	EF_MIPS_PIC		0x00000002	/* Contains PIC code */
+#define	EF_MIPS_CPIC		0x00000004	/* STD PIC calling sequence */
+#define	EF_MIPS_UCODE		0x00000010
+#define	EF_MIPS_ABI2		0x00000020	/* N32 */
+#define	EF_MIPS_OPTIONS_FIRST	0x00000080
+#define	EF_MIPS_ABI		0x0000F000
+#define	EF_MIPS_ABI_O32		0x00001000
+#define	EF_MIPS_ABI_O64		0x00002000
+#define	EF_MIPS_ABI_EABI32	0x00003000
+#define	EF_MIPS_ABI_EABI64	0x00004000
+#define	EF_MIPS_ARCH_ASE	0x0F000000	/* Architectural extensions */
+#define	EF_MIPS_ARCH_ASE_MDMX	0x08000000	/* MDMX multimedia extension */
+#define	EF_MIPS_ARCH_ASE_M16	0x04000000	/* MIPS-16 ISA extensions */
+#define	EF_MIPS_ARCH		0xF0000000	/* Architecture field */
+#define	EF_MIPS_ARCH_1		0x00000000	/* -mips1 code */
+#define	EF_MIPS_ARCH_2		0x10000000	/* -mips2 code */
+#define	EF_MIPS_ARCH_3		0x20000000	/* -mips3 code */
+#define	EF_MIPS_ARCH_4		0x30000000	/* -mips4 code */
+#define	EF_MIPS_ARCH_5		0x40000000	/* -mips5 code */
+#define	EF_MIPS_ARCH_32		0x50000000	/* -mips32 code */
+#define	EF_MIPS_ARCH_64		0x60000000	/* -mips64 code */
+#define	EF_MIPS_ARCH_32R2	0x70000000	/* -mips32r2 code */
+#define	EF_MIPS_ARCH_64R2	0x80000000	/* -mips64r2 code */
+
+#define	EF_PPC_EMB		0x80000000
+#define	EF_PPC_RELOCATABLE	0x00010000
+#define	EF_PPC_RELOCATABLE_LIB	0x00008000
+
+#define	EF_RISCV_RVC		0x00000001
+#define	EF_RISCV_FLOAT_ABI_MASK	0x00000006
+#define	EF_RISCV_FLOAT_ABI_SOFT	0x00000000
+#define	EF_RISCV_FLOAT_ABI_SINGLE 0x000002
+#define	EF_RISCV_FLOAT_ABI_DOUBLE 0x000004
+#define	EF_RISCV_FLOAT_ABI_QUAD	0x00000006
+#define	EF_RISCV_RVE		0x00000008
+#define	EF_RISCV_TSO		0x00000010
+
+#define	EF_SPARC_EXT_MASK	0x00ffff00
+#define	EF_SPARC_32PLUS		0x00000100
+#define	EF_SPARC_SUN_US1	0x00000200
+#define	EF_SPARC_HAL_R1		0x00000200
+#define	EF_SPARC_SUN_US3	0x00000800
+
+#define	EF_SPARCV9_MM		0x00000003
+#define	EF_SPARCV9_TSO		0x00000000
+#define	EF_SPARCV9_PSO		0x00000001
+#define	EF_SPARCV9_RMO		0x00000002
+
+/* Special section indexes. */
+#define	SHN_UNDEF	     0		/* Undefined, missing, irrelevant. */
+#define	SHN_LORESERVE	0xff00		/* First of reserved range. */
+#define	SHN_LOPROC	0xff00		/* First processor-specific. */
+#define	SHN_HIPROC	0xff1f		/* Last processor-specific. */
+#define	SHN_LOOS	0xff20		/* First operating system-specific. */
+#define	SHN_FBSD_CACHED	SHN_LOOS	/* Transient, for sys/kern/link_elf_obj
+					   linker only: Cached global in local
+					   symtab. */
+#define	SHN_HIOS	0xff3f		/* Last operating system-specific. */
+#define	SHN_ABS		0xfff1		/* Absolute values. */
+#define	SHN_COMMON	0xfff2		/* Common data. */
+#define	SHN_XINDEX	0xffff		/* Escape -- index stored elsewhere. */
+#define	SHN_HIRESERVE	0xffff		/* Last of reserved range. */
+
+/* sh_type */
+#define	SHT_NULL		0	/* inactive */
+#define	SHT_PROGBITS		1	/* program defined information */
+#define	SHT_SYMTAB		2	/* symbol table section */
+#define	SHT_STRTAB		3	/* string table section */
+#define	SHT_RELA		4	/* relocation section with addends */
+#define	SHT_HASH		5	/* symbol hash table section */
+#define	SHT_DYNAMIC		6	/* dynamic section */
+#define	SHT_NOTE		7	/* note section */
+#define	SHT_NOBITS		8	/* no space section */
+#define	SHT_REL			9	/* relocation section - no addends */
+#define	SHT_SHLIB		10	/* reserved - purpose unknown */
+#define	SHT_DYNSYM		11	/* dynamic symbol table section */
+#define	SHT_INIT_ARRAY		14	/* Initialization function pointers. */
+#define	SHT_FINI_ARRAY		15	/* Termination function pointers. */
+#define	SHT_PREINIT_ARRAY	16	/* Pre-initialization function ptrs. */
+#define	SHT_GROUP		17	/* Section group. */
+#define	SHT_SYMTAB_SHNDX	18	/* Section indexes (see SHN_XINDEX). */
+#define	SHT_LOOS		0x60000000	/* First of OS specific semantics */
+#define	SHT_LOSUNW		0x6ffffff4
+#define	SHT_SUNW_dof		0x6ffffff4
+#define	SHT_SUNW_cap		0x6ffffff5
+#define	SHT_GNU_ATTRIBUTES	0x6ffffff5
+#define	SHT_SUNW_SIGNATURE	0x6ffffff6
+#define	SHT_GNU_HASH		0x6ffffff6
+#define	SHT_GNU_LIBLIST		0x6ffffff7
+#define	SHT_SUNW_ANNOTATE	0x6ffffff7
+#define	SHT_SUNW_DEBUGSTR	0x6ffffff8
+#define	SHT_SUNW_DEBUG		0x6ffffff9
+#define	SHT_SUNW_move		0x6ffffffa
+#define	SHT_SUNW_COMDAT		0x6ffffffb
+#define	SHT_SUNW_syminfo	0x6ffffffc
+#define	SHT_SUNW_verdef		0x6ffffffd
+#define	SHT_GNU_verdef		0x6ffffffd	/* Symbol versions provided */
+#define	SHT_SUNW_verneed	0x6ffffffe
+#define	SHT_GNU_verneed		0x6ffffffe	/* Symbol versions required */
+#define	SHT_SUNW_versym		0x6fffffff
+#define	SHT_GNU_versym		0x6fffffff	/* Symbol version table */
+#define	SHT_HISUNW		0x6fffffff
+#define	SHT_HIOS		0x6fffffff	/* Last of OS specific semantics */
+#define	SHT_LOPROC		0x70000000	/* reserved range for processor */
+#define	SHT_X86_64_UNWIND	0x70000001	/* unwind information */
+#define	SHT_AMD64_UNWIND	SHT_X86_64_UNWIND 
+
+#define	SHT_ARM_EXIDX		0x70000001	/* Exception index table. */
+#define	SHT_ARM_PREEMPTMAP	0x70000002	/* BPABI DLL dynamic linking 
+						   pre-emption map. */
+#define	SHT_ARM_ATTRIBUTES	0x70000003	/* Object file compatibility 
+						   attributes. */
+#define	SHT_ARM_DEBUGOVERLAY	0x70000004	/* See DBGOVL for details. */
+#define	SHT_ARM_OVERLAYSECTION	0x70000005	/* See DBGOVL for details. */
+#define	SHT_MIPS_LIBLIST	0x70000000
+#define	SHT_MIPS_MSYM		0x70000001
+#define	SHT_MIPS_CONFLICT	0x70000002
+#define	SHT_MIPS_GPTAB		0x70000003
+#define	SHT_MIPS_UCODE		0x70000004
+#define	SHT_MIPS_DEBUG		0x70000005
+#define	SHT_MIPS_REGINFO	0x70000006
+#define	SHT_MIPS_PACKAGE	0x70000007
+#define	SHT_MIPS_PACKSYM	0x70000008
+#define	SHT_MIPS_RELD		0x70000009
+#define	SHT_MIPS_IFACE		0x7000000b
+#define	SHT_MIPS_CONTENT	0x7000000c
+#define	SHT_MIPS_OPTIONS	0x7000000d
+#define	SHT_MIPS_DELTASYM	0x7000001b
+#define	SHT_MIPS_DELTAINST	0x7000001c
+#define	SHT_MIPS_DELTACLASS	0x7000001d
+#define	SHT_MIPS_DWARF		0x7000001e	/* MIPS gcc uses MIPS_DWARF */
+#define	SHT_MIPS_DELTADECL	0x7000001f
+#define	SHT_MIPS_SYMBOL_LIB	0x70000020
+#define	SHT_MIPS_EVENTS		0x70000021
+#define	SHT_MIPS_TRANSLATE	0x70000022
+#define	SHT_MIPS_PIXIE		0x70000023
+#define	SHT_MIPS_XLATE		0x70000024
+#define	SHT_MIPS_XLATE_DEBUG	0x70000025
+#define	SHT_MIPS_WHIRL		0x70000026
+#define	SHT_MIPS_EH_REGION	0x70000027
+#define	SHT_MIPS_XLATE_OLD	0x70000028
+#define	SHT_MIPS_PDR_EXCEPTION	0x70000029
+#define	SHT_MIPS_ABIFLAGS	0x7000002a
+
+#define	SHT_SPARC_GOTDATA	0x70000000
+
+#define	SHTORDERED
+#define	SHT_HIPROC		0x7fffffff	/* specific section header types */
+#define	SHT_LOUSER		0x80000000	/* reserved range for application */
+#define	SHT_HIUSER		0xffffffff	/* specific indexes */
+
+/* Flags for sh_flags. */
+#define	SHF_WRITE		0x1	/* Section contains writable data. */
+#define	SHF_ALLOC		0x2	/* Section occupies memory. */
+#define	SHF_EXECINSTR		0x4	/* Section contains instructions. */
+#define	SHF_MERGE		0x10	/* Section may be merged. */
+#define	SHF_STRINGS		0x20	/* Section contains strings. */
+#define	SHF_INFO_LINK		0x40	/* sh_info holds section index. */
+#define	SHF_LINK_ORDER		0x80	/* Special ordering requirements. */
+#define	SHF_OS_NONCONFORMING	0x100	/* OS-specific processing required. */
+#define	SHF_GROUP		0x200	/* Member of section group. */
+#define	SHF_TLS			0x400	/* Section contains TLS data. */
+#define	SHF_COMPRESSED		0x800	/* Section contains compressed data. */
+#define	SHF_MASKOS	0x0ff00000	/* OS-specific semantics. */
+#define	SHF_MASKPROC	0xf0000000	/* Processor-specific semantics. */
+
+/* Flags for section groups. */
+#define	GRP_COMDAT	0x1	/* COMDAT semantics. */
+
+/*
+ * Flags / mask for .gnu.versym sections.
+ */
+#define	VERSYM_VERSION	0x7fff
+#define	VERSYM_HIDDEN	0x8000
+
+/* Values for p_type. */
+#define	PT_NULL		0	/* Unused entry. */
+#define	PT_LOAD		1	/* Loadable segment. */
+#define	PT_DYNAMIC	2	/* Dynamic linking information segment. */
+#define	PT_INTERP	3	/* Pathname of interpreter. */
+#define	PT_NOTE		4	/* Auxiliary information. */
+#define	PT_SHLIB	5	/* Reserved (not used). */
+#define	PT_PHDR		6	/* Location of program header itself. */
+#define	PT_TLS		7	/* Thread local storage segment */
+#define	PT_LOOS		0x60000000	/* First OS-specific. */
+#define	PT_SUNW_UNWIND	0x6464e550	/* amd64 UNWIND program header */
+#define	PT_DUMP_DELTA	0x6fb5d000	/* va->pa map for kernel dumps
+					   (currently arm). */
+#define	PT_LOSUNW	0x6ffffffa
+#define	PT_SUNWBSS	0x6ffffffa	/* Sun Specific segment */
+#define	PT_SUNWSTACK	0x6ffffffb	/* describes the stack segment */
+#define	PT_SUNWDTRACE	0x6ffffffc	/* private */
+#define	PT_SUNWCAP	0x6ffffffd	/* hard/soft capabilities segment */
+#define	PT_HISUNW	0x6fffffff
+#define	PT_HIOS		0x6fffffff	/* Last OS-specific. */
+#define	PT_LOPROC	0x70000000	/* First processor-specific type. */
+#define	PT_ARM_ARCHEXT	0x70000000	/* ARM arch compat information. */
+#define	PT_ARM_EXIDX	0x70000001	/* ARM exception unwind tables. */
+#define	PT_MIPS_REGINFO		0x70000000	/* MIPS register usage info */
+#define	PT_MIPS_RTPROC		0x70000001	/* MIPS runtime procedure tbl */
+#define	PT_MIPS_OPTIONS		0x70000002	/* MIPS e_flags value*/
+#define	PT_MIPS_ABIFLAGS	0x70000003	/* MIPS fp mode */
+#define	PT_HIPROC	0x7fffffff	/* Last processor-specific type. */
+
+#define	PT_OPENBSD_RANDOMIZE	0x65A3DBE6	/* OpenBSD random data segment */
+#define	PT_OPENBSD_WXNEEDED	0x65A3DBE7	/* OpenBSD EXEC/WRITE pages needed */
+#define	PT_OPENBSD_BOOTDATA	0x65A41BE6	/* OpenBSD section for boot args */
+
+/* Values for p_flags. */
+#define	PF_X		0x1		/* Executable. */
+#define	PF_W		0x2		/* Writable. */
+#define	PF_R		0x4		/* Readable. */
+#define	PF_MASKOS	0x0ff00000	/* Operating system-specific. */
+#define	PF_MASKPROC	0xf0000000	/* Processor-specific. */
+
+/* Extended program header index. */
+#define	PN_XNUM		0xffff
+
+/* Values for d_tag. */
+#define	DT_NULL		0	/* Terminating entry. */
+#define	DT_NEEDED	1	/* String table offset of a needed shared
+				   library. */
+#define	DT_PLTRELSZ	2	/* Total size in bytes of PLT relocations. */
+#define	DT_PLTGOT	3	/* Processor-dependent address. */
+#define	DT_HASH		4	/* Address of symbol hash table. */
+#define	DT_STRTAB	5	/* Address of string table. */
+#define	DT_SYMTAB	6	/* Address of symbol table. */
+#define	DT_RELA		7	/* Address of ElfNN_Rela relocations. */
+#define	DT_RELASZ	8	/* Total size of ElfNN_Rela relocations. */
+#define	DT_RELAENT	9	/* Size of each ElfNN_Rela relocation entry. */
+#define	DT_STRSZ	10	/* Size of string table. */
+#define	DT_SYMENT	11	/* Size of each symbol table entry. */
+#define	DT_INIT		12	/* Address of initialization function. */
+#define	DT_FINI		13	/* Address of finalization function. */
+#define	DT_SONAME	14	/* String table offset of shared object
+				   name. */
+#define	DT_RPATH	15	/* String table offset of library path. [sup] */
+#define	DT_SYMBOLIC	16	/* Indicates "symbolic" linking. [sup] */
+#define	DT_REL		17	/* Address of ElfNN_Rel relocations. */
+#define	DT_RELSZ	18	/* Total size of ElfNN_Rel relocations. */
+#define	DT_RELENT	19	/* Size of each ElfNN_Rel relocation. */
+#define	DT_PLTREL	20	/* Type of relocation used for PLT. */
+#define	DT_DEBUG	21	/* Reserved (not used). */
+#define	DT_TEXTREL	22	/* Indicates there may be relocations in
+				   non-writable segments. [sup] */
+#define	DT_JMPREL	23	/* Address of PLT relocations. */
+#define	DT_BIND_NOW	24	/* [sup] */
+#define	DT_INIT_ARRAY	25	/* Address of the array of pointers to
+				   initialization functions */
+#define	DT_FINI_ARRAY	26	/* Address of the array of pointers to
+				   termination functions */
+#define	DT_INIT_ARRAYSZ	27	/* Size in bytes of the array of
+				   initialization functions. */
+#define	DT_FINI_ARRAYSZ	28	/* Size in bytes of the array of
+				   termination functions. */
+#define	DT_RUNPATH	29	/* String table offset of a null-terminated
+				   library search path string. */
+#define	DT_FLAGS	30	/* Object specific flag values. */
+#define	DT_ENCODING	32	/* Values greater than or equal to DT_ENCODING
+				   and less than DT_LOOS follow the rules for
+				   the interpretation of the d_un union
+				   as follows: even == 'd_ptr', odd == 'd_val'
+				   or none */
+#define	DT_PREINIT_ARRAY 32	/* Address of the array of pointers to
+				   pre-initialization functions. */
+#define	DT_PREINIT_ARRAYSZ 33	/* Size in bytes of the array of
+				   pre-initialization functions. */
+#define	DT_MAXPOSTAGS	34	/* number of positive tags */
+#define	DT_RELRSZ	35	/* Total size of ElfNN_Relr relocations. */
+#define	DT_RELR		36	/* Address of ElfNN_Relr relocations. */
+#define	DT_RELRENT	37	/* Size of each ElfNN_Relr relocation. */
+#define	DT_LOOS		0x6000000d	/* First OS-specific */
+#define	DT_SUNW_AUXILIARY	0x6000000d	/* symbol auxiliary name */
+#define	DT_SUNW_RTLDINF		0x6000000e	/* ld.so.1 info (private) */
+#define	DT_SUNW_FILTER		0x6000000f	/* symbol filter name */
+#define	DT_SUNW_CAP		0x60000010	/* hardware/software */
+#define	DT_SUNW_ASLR		0x60000023	/* ASLR control */
+#define	DT_HIOS		0x6ffff000	/* Last OS-specific */
+
+/*
+ * DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the
+ * Dyn.d_un.d_val field of the Elf*_Dyn structure.
+ */
+#define	DT_VALRNGLO	0x6ffffd00
+#define	DT_GNU_PRELINKED	0x6ffffdf5 /* prelinking timestamp */
+#define	DT_GNU_CONFLICTSZ	0x6ffffdf6 /* size of conflict section */
+#define	DT_GNU_LIBLISTSZ	0x6ffffdf7 /* size of library list */
+#define	DT_CHECKSUM	0x6ffffdf8	/* elf checksum */
+#define	DT_PLTPADSZ	0x6ffffdf9	/* pltpadding size */
+#define	DT_MOVEENT	0x6ffffdfa	/* move table entry size */
+#define	DT_MOVESZ	0x6ffffdfb	/* move table size */
+#define	DT_FEATURE	0x6ffffdfc	/* feature holder */
+#define	DT_FEATURE_1	DT_FEATURE
+#define	DT_POSFLAG_1	0x6ffffdfd	/* flags for DT_* entries, effecting */
+					/*	the following DT_* entry. */
+					/*	See DF_P1_* definitions */
+#define	DT_SYMINSZ	0x6ffffdfe	/* syminfo table size (in bytes) */
+#define	DT_SYMINENT	0x6ffffdff	/* syminfo entry size (in bytes) */
+#define	DT_VALRNGHI	0x6ffffdff
+
+/*
+ * DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the
+ * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.
+ *
+ * If any adjustment is made to the ELF object after it has been
+ * built, these entries will need to be adjusted.
+ */
+#define	DT_ADDRRNGLO	0x6ffffe00
+#define	DT_GNU_HASH	0x6ffffef5	/* GNU-style hash table */
+#define	DT_TLSDESC_PLT	0x6ffffef6	/* loc. of PLT for tlsdesc resolver */
+#define	DT_TLSDESC_GOT	0x6ffffef7	/* loc. of GOT for tlsdesc resolver */
+#define	DT_GNU_CONFLICT	0x6ffffef8	/* address of conflict section */
+#define	DT_GNU_LIBLIST	0x6ffffef9	/* address of library list */
+#define	DT_CONFIG	0x6ffffefa	/* configuration information */
+#define	DT_DEPAUDIT	0x6ffffefb	/* dependency auditing */
+#define	DT_AUDIT	0x6ffffefc	/* object auditing */
+#define	DT_PLTPAD	0x6ffffefd	/* pltpadding (sparcv9) */
+#define	DT_MOVETAB	0x6ffffefe	/* move table */
+#define	DT_SYMINFO	0x6ffffeff	/* syminfo table */
+#define	DT_ADDRRNGHI	0x6ffffeff
+
+#define	DT_VERSYM	0x6ffffff0	/* Address of versym section. */
+#define	DT_RELACOUNT	0x6ffffff9	/* number of RELATIVE relocations */
+#define	DT_RELCOUNT	0x6ffffffa	/* number of RELATIVE relocations */
+#define	DT_FLAGS_1	0x6ffffffb	/* state flags - see DF_1_* defs */
+#define	DT_VERDEF	0x6ffffffc	/* Address of verdef section. */
+#define	DT_VERDEFNUM	0x6ffffffd	/* Number of elems in verdef section */
+#define	DT_VERNEED	0x6ffffffe	/* Address of verneed section. */
+#define	DT_VERNEEDNUM	0x6fffffff	/* Number of elems in verneed section */
+
+#define	DT_LOPROC	0x70000000	/* First processor-specific type. */
+
+#define	DT_AARCH64_BTI_PLT		0x70000001
+#define	DT_AARCH64_PAC_PLT		0x70000003
+#define	DT_AARCH64_VARIANT_PCS		0x70000005
+
+#define	DT_ARM_SYMTABSZ			0x70000001
+#define	DT_ARM_PREEMPTMAP		0x70000002
+
+#define	DT_SPARC_REGISTER		0x70000001
+#define	DT_DEPRECATED_SPARC_REGISTER	0x7000001
+
+#define	DT_MIPS_RLD_VERSION		0x70000001
+#define	DT_MIPS_TIME_STAMP		0x70000002
+#define	DT_MIPS_ICHECKSUM		0x70000003
+#define	DT_MIPS_IVERSION		0x70000004
+#define	DT_MIPS_FLAGS			0x70000005
+#define	DT_MIPS_BASE_ADDRESS		0x70000006
+#define	DT_MIPS_CONFLICT		0x70000008
+#define	DT_MIPS_LIBLIST			0x70000009
+#define	DT_MIPS_LOCAL_GOTNO		0x7000000a
+#define	DT_MIPS_CONFLICTNO		0x7000000b
+#define	DT_MIPS_LIBLISTNO		0x70000010
+#define	DT_MIPS_SYMTABNO		0x70000011
+#define	DT_MIPS_UNREFEXTNO		0x70000012
+#define	DT_MIPS_GOTSYM			0x70000013
+#define	DT_MIPS_HIPAGENO		0x70000014
+#define	DT_MIPS_RLD_MAP			0x70000016
+#define	DT_MIPS_DELTA_CLASS		0x70000017
+#define	DT_MIPS_DELTA_CLASS_NO		0x70000018
+#define	DT_MIPS_DELTA_INSTANCE		0x70000019
+#define	DT_MIPS_DELTA_INSTANCE_NO	0x7000001A
+#define	DT_MIPS_DELTA_RELOC		0x7000001B
+#define	DT_MIPS_DELTA_RELOC_NO		0x7000001C
+#define	DT_MIPS_DELTA_SYM		0x7000001D
+#define	DT_MIPS_DELTA_SYM_NO		0x7000001E
+#define	DT_MIPS_DELTA_CLASSSYM		0x70000020
+#define	DT_MIPS_DELTA_CLASSSYM_NO	0x70000021
+#define	DT_MIPS_CXX_FLAGS		0x70000022
+#define	DT_MIPS_PIXIE_INIT		0x70000023
+#define	DT_MIPS_SYMBOL_LIB		0x70000024
+#define	DT_MIPS_LOCALPAGE_GOTIDX	0x70000025
+#define	DT_MIPS_LOCAL_GOTIDX		0x70000026
+#define	DT_MIPS_HIDDEN_GOTIDX		0x70000027
+#define	DT_MIPS_PROTECTED_GOTIDX	0x70000028
+#define	DT_MIPS_OPTIONS			0x70000029
+#define	DT_MIPS_INTERFACE		0x7000002A
+#define	DT_MIPS_DYNSTR_ALIGN		0x7000002B
+#define	DT_MIPS_INTERFACE_SIZE		0x7000002C
+#define	DT_MIPS_RLD_TEXT_RESOLVE_ADDR	0x7000002D
+#define	DT_MIPS_PERF_SUFFIX		0x7000002E
+#define	DT_MIPS_COMPACT_SIZE		0x7000002F
+#define	DT_MIPS_GP_VALUE		0x70000030
+#define	DT_MIPS_AUX_DYNAMIC		0x70000031
+#define	DT_MIPS_PLTGOT			0x70000032
+#define	DT_MIPS_RLD_OBJ_UPDATE		0x70000033
+#define	DT_MIPS_RWPLT			0x70000034
+#define	DT_MIPS_RLD_MAP_REL		0x70000035
+
+#define	DT_PPC_GOT			0x70000000
+#define	DT_PPC_TLSOPT			0x70000001
+
+#define	DT_PPC64_GLINK			0x70000000
+#define	DT_PPC64_OPD			0x70000001
+#define	DT_PPC64_OPDSZ			0x70000002
+#define	DT_PPC64_TLSOPT			0x70000003
+
+#define	DT_AUXILIARY	0x7ffffffd	/* shared library auxiliary name */
+#define	DT_USED		0x7ffffffe	/* ignored - same as needed */
+#define	DT_FILTER	0x7fffffff	/* shared library filter name */
+#define	DT_HIPROC	0x7fffffff	/* Last processor-specific type. */
+
+/* Values for DT_FLAGS */
+#define	DF_ORIGIN	0x0001	/* Indicates that the object being loaded may
+				   make reference to the $ORIGIN substitution
+				   string */
+#define	DF_SYMBOLIC	0x0002	/* Indicates "symbolic" linking. */
+#define	DF_TEXTREL	0x0004	/* Indicates there may be relocations in
+				   non-writable segments. */
+#define	DF_BIND_NOW	0x0008	/* Indicates that the dynamic linker should
+				   process all relocations for the object
+				   containing this entry before transferring
+				   control to the program. */
+#define	DF_STATIC_TLS	0x0010	/* Indicates that the shared object or
+				   executable contains code using a static
+				   thread-local storage scheme. */
+
+/* Values for DT_FLAGS_1 */
+#define	DF_1_BIND_NOW	0x00000001	/* Same as DF_BIND_NOW */
+#define	DF_1_GLOBAL	0x00000002	/* Set the RTLD_GLOBAL for object */
+#define	DF_1_NODELETE	0x00000008	/* Set the RTLD_NODELETE for object */
+#define	DF_1_LOADFLTR	0x00000010	/* Immediate loading of filtees */
+#define	DF_1_NOOPEN     0x00000040	/* Do not allow loading on dlopen() */
+#define	DF_1_ORIGIN	0x00000080	/* Process $ORIGIN */
+#define	DF_1_INTERPOSE	0x00000400	/* Interpose all objects but main */
+#define	DF_1_NODEFLIB	0x00000800	/* Do not search default paths */
+#define	DF_1_PIE	0x08000000	/* Is position-independent executable */
+
+/* Values for l_flags. */
+#define	LL_NONE			0x0	/* no flags */
+#define	LL_EXACT_MATCH		0x1	/* require an exact match */
+#define	LL_IGNORE_INT_VER	0x2	/* ignore version incompatibilities */
+#define	LL_REQUIRE_MINOR	0x4
+#define	LL_EXPORTS		0x8
+#define	LL_DELAY_LOAD		0x10
+#define	LL_DELTA		0x20
+
+/* Note section names */
+#define	ELF_NOTE_FREEBSD	"FreeBSD"
+#define	ELF_NOTE_NETBSD		"NetBSD"
+#define	ELF_NOTE_SOLARIS	"SUNW Solaris"
+#define	ELF_NOTE_GNU		"GNU"
+
+/* Values for n_type used in executables. */
+#define	NT_FREEBSD_ABI_TAG	1
+#define	NT_FREEBSD_NOINIT_TAG	2
+#define	NT_FREEBSD_ARCH_TAG	3
+#define	NT_FREEBSD_FEATURE_CTL	4
+
+/* NT_FREEBSD_FEATURE_CTL desc[0] bits */
+#define	NT_FREEBSD_FCTL_ASLR_DISABLE	0x00000001
+#define	NT_FREEBSD_FCTL_PROTMAX_DISABLE	0x00000002
+#define	NT_FREEBSD_FCTL_STKGAP_DISABLE	0x00000004
+#define	NT_FREEBSD_FCTL_WXNEEDED	0x00000008
+#define	NT_FREEBSD_FCTL_LA48		0x00000010
+/* was ASG_DISABLE, do not reuse	0x00000020 */
+
+/* Values for n_type.  Used in core files. */
+#define	NT_PRSTATUS	1	/* Process status. */
+#define	NT_FPREGSET	2	/* Floating point registers. */
+#define	NT_PRPSINFO	3	/* Process state info. */
+#define	NT_THRMISC	7	/* Thread miscellaneous info. */
+#define	NT_PROCSTAT_PROC	8	/* Procstat proc data. */
+#define	NT_PROCSTAT_FILES	9	/* Procstat files data. */
+#define	NT_PROCSTAT_VMMAP	10	/* Procstat vmmap data. */
+#define	NT_PROCSTAT_GROUPS	11	/* Procstat groups data. */
+#define	NT_PROCSTAT_UMASK	12	/* Procstat umask data. */
+#define	NT_PROCSTAT_RLIMIT	13	/* Procstat rlimit data. */
+#define	NT_PROCSTAT_OSREL	14	/* Procstat osreldate data. */
+#define	NT_PROCSTAT_PSSTRINGS	15	/* Procstat ps_strings data. */
+#define	NT_PROCSTAT_AUXV	16	/* Procstat auxv data. */
+#define	NT_PTLWPINFO		17	/* Thread ptrace miscellaneous info. */
+#define	NT_PPC_VMX	0x100	/* PowerPC Altivec/VMX registers */
+#define	NT_PPC_VSX	0x102	/* PowerPC VSX registers */
+#define	NT_X86_SEGBASES	0x200	/* x86 FS/GS base addresses. */
+#define	NT_X86_XSTATE	0x202	/* x86 XSAVE extended state. */
+#define	NT_ARM_VFP	0x400	/* ARM VFP registers */
+#define	NT_ARM_TLS	0x401	/* ARM TLS register */
+#define	NT_ARM_ADDR_MASK	0x406	/* arm64 address mask (e.g. for TBI) */
+
+/* GNU note types. */
+#define	NT_GNU_ABI_TAG		1
+#define	NT_GNU_HWCAP		2
+#define	NT_GNU_BUILD_ID		3
+#define	NT_GNU_GOLD_VERSION	4
+#define	NT_GNU_PROPERTY_TYPE_0	5
+
+#define	GNU_PROPERTY_LOPROC			0xc0000000
+#define	GNU_PROPERTY_HIPROC			0xdfffffff
+
+#define	GNU_PROPERTY_AARCH64_FEATURE_1_AND	0xc0000000
+
+#define	GNU_PROPERTY_AARCH64_FEATURE_1_PAC	0x00000002
+
+#define	GNU_PROPERTY_X86_FEATURE_1_AND		0xc0000002
+
+#define	GNU_PROPERTY_X86_FEATURE_1_IBT		0x00000001
+#define	GNU_PROPERTY_X86_FEATURE_1_SHSTK	0x00000002
+
+/* Symbol Binding - ELFNN_ST_BIND - st_info */
+#define	STB_LOCAL	0	/* Local symbol */
+#define	STB_GLOBAL	1	/* Global symbol */
+#define	STB_WEAK	2	/* like global - lower precedence */
+#define	STB_LOOS	10	/* Start of operating system reserved range. */
+#define	STB_GNU_UNIQUE	10	/* Unique symbol (GNU) */
+#define	STB_HIOS	12	/* End of operating system reserved range. */
+#define	STB_LOPROC	13	/* reserved range for processor */
+#define	STB_HIPROC	15	/*   specific semantics. */
+
+/* Symbol type - ELFNN_ST_TYPE - st_info */
+#define	STT_NOTYPE	0	/* Unspecified type. */
+#define	STT_OBJECT	1	/* Data object. */
+#define	STT_FUNC	2	/* Function. */
+#define	STT_SECTION	3	/* Section. */
+#define	STT_FILE	4	/* Source file. */
+#define	STT_COMMON	5	/* Uninitialized common block. */
+#define	STT_TLS		6	/* TLS object. */
+#define	STT_NUM		7
+#define	STT_LOOS	10	/* Reserved range for operating system */
+#define	STT_GNU_IFUNC	10
+#define	STT_HIOS	12	/*   specific semantics. */
+#define	STT_LOPROC	13	/* Start of processor reserved range. */
+#define	STT_SPARC_REGISTER 13	/* SPARC register information. */
+#define	STT_HIPROC	15	/* End of processor reserved range. */
+
+/* Symbol visibility - ELFNN_ST_VISIBILITY - st_other */
+#define	STV_DEFAULT	0x0	/* Default visibility (see binding). */
+#define	STV_INTERNAL	0x1	/* Special meaning in relocatable objects. */
+#define	STV_HIDDEN	0x2	/* Not visible. */
+#define	STV_PROTECTED	0x3	/* Visible but not preemptible. */
+#define	STV_EXPORTED	0x4
+#define	STV_SINGLETON	0x5
+#define	STV_ELIMINATE	0x6
+
+/* Special symbol table indexes. */
+#define	STN_UNDEF	0	/* Undefined symbol index. */
+
+/* Symbol versioning flags. */
+#define	VER_DEF_CURRENT	1
+#define	VER_DEF_IDX(x)	VER_NDX(x)
+
+#define	VER_FLG_BASE	0x01
+#define	VER_FLG_WEAK	0x02
+
+#define	VER_NEED_CURRENT	1
+#define	VER_NEED_WEAK	(1u << 15)
+#define	VER_NEED_HIDDEN	VER_NDX_HIDDEN
+#define	VER_NEED_IDX(x)	VER_NDX(x)
+
+#define	VER_NDX_LOCAL	0
+#define	VER_NDX_GLOBAL	1
+#define	VER_NDX_GIVEN	2
+
+#define	VER_NDX_HIDDEN	(1u << 15)
+#define	VER_NDX(x)	((x) & ~(1u << 15))
+
+#define	CA_SUNW_NULL	0
+#define	CA_SUNW_HW_1	1		/* first hardware capabilities entry */
+#define	CA_SUNW_SF_1	2		/* first software capabilities entry */
+
+/*
+ * Syminfo flag values
+ */
+#define	SYMINFO_FLG_DIRECT	0x0001	/* symbol ref has direct association */
+					/*	to object containing defn. */
+#define	SYMINFO_FLG_PASSTHRU	0x0002	/* ignored - see SYMINFO_FLG_FILTER */
+#define	SYMINFO_FLG_COPY	0x0004	/* symbol is a copy-reloc */
+#define	SYMINFO_FLG_LAZYLOAD	0x0008	/* object containing defn should be */
+					/*	lazily-loaded */
+#define	SYMINFO_FLG_DIRECTBIND	0x0010	/* ref should be bound directly to */
+					/*	object containing defn. */
+#define	SYMINFO_FLG_NOEXTDIRECT	0x0020	/* don't let an external reference */
+					/*	directly bind to this symbol */
+#define	SYMINFO_FLG_FILTER	0x0002	/* symbol ref is associated to a */
+#define	SYMINFO_FLG_AUXILIARY	0x0040	/* 	standard or auxiliary filter */
+
+/*
+ * Syminfo.si_boundto values.
+ */
+#define	SYMINFO_BT_SELF		0xffff	/* symbol bound to self */
+#define	SYMINFO_BT_PARENT	0xfffe	/* symbol bound to parent */
+#define	SYMINFO_BT_NONE		0xfffd	/* no special symbol binding */
+#define	SYMINFO_BT_EXTERN	0xfffc	/* symbol defined as external */
+#define	SYMINFO_BT_LOWRESERVE	0xff00	/* beginning of reserved entries */
+
+/*
+ * Syminfo version values.
+ */
+#define	SYMINFO_NONE		0	/* Syminfo version */
+#define	SYMINFO_CURRENT		1
+#define	SYMINFO_NUM		2
+
+/* Values for ch_type (compressed section headers). */
+#define	ELFCOMPRESS_ZLIB	1	/* ZLIB/DEFLATE */
+#define	ELFCOMPRESS_ZSTD	2	/* Zstandard */
+#define	ELFCOMPRESS_LOOS	0x60000000	/* OS-specific */
+#define	ELFCOMPRESS_HIOS	0x6fffffff
+#define	ELFCOMPRESS_LOPROC	0x70000000	/* Processor-specific */
+#define	ELFCOMPRESS_HIPROC	0x7fffffff
+
+/*
+ * Relocation types.
+ *
+ * All machine architectures are defined here to allow tools on one to
+ * handle others.
+ */
+
+#define	R_386_NONE		0	/* No relocation. */
+#define	R_386_32		1	/* Add symbol value. */
+#define	R_386_PC32		2	/* Add PC-relative symbol value. */
+#define	R_386_GOT32		3	/* Add PC-relative GOT offset. */
+#define	R_386_PLT32		4	/* Add PC-relative PLT offset. */
+#define	R_386_COPY		5	/* Copy data from shared object. */
+#define	R_386_GLOB_DAT		6	/* Set GOT entry to data address. */
+#define	R_386_JMP_SLOT		7	/* Set GOT entry to code address. */
+#define	R_386_RELATIVE		8	/* Add load address of shared object. */
+#define	R_386_GOTOFF		9	/* Add GOT-relative symbol address. */
+#define	R_386_GOTPC		10	/* Add PC-relative GOT table address. */
+#define	R_386_32PLT		11
+#define	R_386_TLS_TPOFF		14	/* Negative offset in static TLS block */
+#define	R_386_TLS_IE		15	/* Absolute address of GOT for -ve static TLS */
+#define	R_386_TLS_GOTIE		16	/* GOT entry for negative static TLS block */
+#define	R_386_TLS_LE		17	/* Negative offset relative to static TLS */
+#define	R_386_TLS_GD		18	/* 32 bit offset to GOT (index,off) pair */
+#define	R_386_TLS_LDM		19	/* 32 bit offset to GOT (index,zero) pair */
+#define	R_386_16		20
+#define	R_386_PC16		21
+#define	R_386_8			22
+#define	R_386_PC8		23
+#define	R_386_TLS_GD_32		24	/* 32 bit offset to GOT (index,off) pair */
+#define	R_386_TLS_GD_PUSH	25	/* pushl instruction for Sun ABI GD sequence */
+#define	R_386_TLS_GD_CALL	26	/* call instruction for Sun ABI GD sequence */
+#define	R_386_TLS_GD_POP	27	/* popl instruction for Sun ABI GD sequence */
+#define	R_386_TLS_LDM_32	28	/* 32 bit offset to GOT (index,zero) pair */
+#define	R_386_TLS_LDM_PUSH	29	/* pushl instruction for Sun ABI LD sequence */
+#define	R_386_TLS_LDM_CALL	30	/* call instruction for Sun ABI LD sequence */
+#define	R_386_TLS_LDM_POP	31	/* popl instruction for Sun ABI LD sequence */
+#define	R_386_TLS_LDO_32	32	/* 32 bit offset from start of TLS block */
+#define	R_386_TLS_IE_32		33	/* 32 bit offset to GOT static TLS offset entry */
+#define	R_386_TLS_LE_32		34	/* 32 bit offset within static TLS block */
+#define	R_386_TLS_DTPMOD32	35	/* GOT entry containing TLS index */
+#define	R_386_TLS_DTPOFF32	36	/* GOT entry containing TLS offset */
+#define	R_386_TLS_TPOFF32	37	/* GOT entry of -ve static TLS offset */
+#define	R_386_SIZE32		38
+#define	R_386_TLS_GOTDESC	39
+#define	R_386_TLS_DESC_CALL	40
+#define	R_386_TLS_DESC		41
+#define	R_386_IRELATIVE		42	/* PLT entry resolved indirectly at runtime */
+#define	R_386_GOT32X		43
+
+#define	R_AARCH64_NONE		0	/* No relocation */
+#define	R_AARCH64_ABS64		257	/* Absolute offset */
+#define	R_AARCH64_ABS32		258	/* Absolute, 32-bit overflow check */
+#define	R_AARCH64_ABS16		259	/* Absolute, 16-bit overflow check */
+#define	R_AARCH64_PREL64	260	/* PC relative */
+#define	R_AARCH64_PREL32	261	/* PC relative, 32-bit overflow check */
+#define	R_AARCH64_PREL16	262	/* PC relative, 16-bit overflow check */
+#define	R_AARCH64_TSTBR14	279	/* TBZ/TBNZ immediate */
+#define	R_AARCH64_CONDBR19	280	/* Conditional branch immediate */
+#define	R_AARCH64_JUMP26	282	/* Branch immediate */
+#define	R_AARCH64_CALL26	283	/* Call immediate */
+#define	R_AARCH64_COPY		1024	/* Copy data from shared object */
+#define	R_AARCH64_GLOB_DAT	1025	/* Set GOT entry to data address */
+#define	R_AARCH64_JUMP_SLOT	1026	/* Set GOT entry to code address */
+#define	R_AARCH64_RELATIVE 	1027	/* Add load address of shared object */
+#define	R_AARCH64_TLS_DTPREL64	1028
+#define	R_AARCH64_TLS_DTPMOD64	1029
+#define	R_AARCH64_TLS_TPREL64 	1030
+#define	R_AARCH64_TLSDESC 	1031	/* Identify the TLS descriptor */
+#define	R_AARCH64_IRELATIVE	1032
+
+#define	R_ARM_NONE		0	/* No relocation. */
+#define	R_ARM_PC24		1
+#define	R_ARM_ABS32		2
+#define	R_ARM_REL32		3
+#define	R_ARM_PC13		4
+#define	R_ARM_ABS16		5
+#define	R_ARM_ABS12		6
+#define	R_ARM_THM_ABS5		7
+#define	R_ARM_ABS8		8
+#define	R_ARM_SBREL32		9
+#define	R_ARM_THM_PC22		10
+#define	R_ARM_THM_PC8		11
+#define	R_ARM_AMP_VCALL9	12
+#define	R_ARM_SWI24		13
+#define	R_ARM_THM_SWI8		14
+#define	R_ARM_XPC25		15
+#define	R_ARM_THM_XPC22		16
+/* TLS relocations */
+#define	R_ARM_TLS_DTPMOD32	17	/* ID of module containing symbol */
+#define	R_ARM_TLS_DTPOFF32	18	/* Offset in TLS block */
+#define	R_ARM_TLS_TPOFF32	19	/* Offset in static TLS block */
+#define	R_ARM_COPY		20	/* Copy data from shared object. */
+#define	R_ARM_GLOB_DAT		21	/* Set GOT entry to data address. */
+#define	R_ARM_JUMP_SLOT		22	/* Set GOT entry to code address. */
+#define	R_ARM_RELATIVE		23	/* Add load address of shared object. */
+#define	R_ARM_GOTOFF		24	/* Add GOT-relative symbol address. */
+#define	R_ARM_GOTPC		25	/* Add PC-relative GOT table address. */
+#define	R_ARM_GOT32		26	/* Add PC-relative GOT offset. */
+#define	R_ARM_PLT32		27	/* Add PC-relative PLT offset. */
+#define	R_ARM_GNU_VTENTRY	100
+#define	R_ARM_GNU_VTINHERIT	101
+#define	R_ARM_RSBREL32		250
+#define	R_ARM_THM_RPC22		251
+#define	R_ARM_RREL32		252
+#define	R_ARM_RABS32		253
+#define	R_ARM_RPC24		254
+#define	R_ARM_RBASE		255
+
+/*	Name			Value	   Field	Calculation */
+#define	R_IA_64_NONE		0	/* None */
+#define	R_IA_64_IMM14		0x21	/* immediate14	S + A */
+#define	R_IA_64_IMM22		0x22	/* immediate22	S + A */
+#define	R_IA_64_IMM64		0x23	/* immediate64	S + A */
+#define	R_IA_64_DIR32MSB	0x24	/* word32 MSB	S + A */
+#define	R_IA_64_DIR32LSB	0x25	/* word32 LSB	S + A */
+#define	R_IA_64_DIR64MSB	0x26	/* word64 MSB	S + A */
+#define	R_IA_64_DIR64LSB	0x27	/* word64 LSB	S + A */
+#define	R_IA_64_GPREL22		0x2a	/* immediate22	@gprel(S + A) */
+#define	R_IA_64_GPREL64I	0x2b	/* immediate64	@gprel(S + A) */
+#define	R_IA_64_GPREL32MSB	0x2c	/* word32 MSB	@gprel(S + A) */
+#define	R_IA_64_GPREL32LSB	0x2d	/* word32 LSB	@gprel(S + A) */
+#define	R_IA_64_GPREL64MSB	0x2e	/* word64 MSB	@gprel(S + A) */
+#define	R_IA_64_GPREL64LSB	0x2f	/* word64 LSB	@gprel(S + A) */
+#define	R_IA_64_LTOFF22		0x32	/* immediate22	@ltoff(S + A) */
+#define	R_IA_64_LTOFF64I	0x33	/* immediate64	@ltoff(S + A) */
+#define	R_IA_64_PLTOFF22	0x3a	/* immediate22	@pltoff(S + A) */
+#define	R_IA_64_PLTOFF64I	0x3b	/* immediate64	@pltoff(S + A) */
+#define	R_IA_64_PLTOFF64MSB	0x3e	/* word64 MSB	@pltoff(S + A) */
+#define	R_IA_64_PLTOFF64LSB	0x3f	/* word64 LSB	@pltoff(S + A) */
+#define	R_IA_64_FPTR64I		0x43	/* immediate64	@fptr(S + A) */
+#define	R_IA_64_FPTR32MSB	0x44	/* word32 MSB	@fptr(S + A) */
+#define	R_IA_64_FPTR32LSB	0x45	/* word32 LSB	@fptr(S + A) */
+#define	R_IA_64_FPTR64MSB	0x46	/* word64 MSB	@fptr(S + A) */
+#define	R_IA_64_FPTR64LSB	0x47	/* word64 LSB	@fptr(S + A) */
+#define	R_IA_64_PCREL60B	0x48	/* immediate60 form1 S + A - P */
+#define	R_IA_64_PCREL21B	0x49	/* immediate21 form1 S + A - P */
+#define	R_IA_64_PCREL21M	0x4a	/* immediate21 form2 S + A - P */
+#define	R_IA_64_PCREL21F	0x4b	/* immediate21 form3 S + A - P */
+#define	R_IA_64_PCREL32MSB	0x4c	/* word32 MSB	S + A - P */
+#define	R_IA_64_PCREL32LSB	0x4d	/* word32 LSB	S + A - P */
+#define	R_IA_64_PCREL64MSB	0x4e	/* word64 MSB	S + A - P */
+#define	R_IA_64_PCREL64LSB	0x4f	/* word64 LSB	S + A - P */
+#define	R_IA_64_LTOFF_FPTR22	0x52	/* immediate22	@ltoff(@fptr(S + A)) */
+#define	R_IA_64_LTOFF_FPTR64I	0x53	/* immediate64	@ltoff(@fptr(S + A)) */
+#define	R_IA_64_LTOFF_FPTR32MSB	0x54	/* word32 MSB	@ltoff(@fptr(S + A)) */
+#define	R_IA_64_LTOFF_FPTR32LSB	0x55	/* word32 LSB	@ltoff(@fptr(S + A)) */
+#define	R_IA_64_LTOFF_FPTR64MSB	0x56	/* word64 MSB	@ltoff(@fptr(S + A)) */
+#define	R_IA_64_LTOFF_FPTR64LSB	0x57	/* word64 LSB	@ltoff(@fptr(S + A)) */
+#define	R_IA_64_SEGREL32MSB	0x5c	/* word32 MSB	@segrel(S + A) */
+#define	R_IA_64_SEGREL32LSB	0x5d	/* word32 LSB	@segrel(S + A) */
+#define	R_IA_64_SEGREL64MSB	0x5e	/* word64 MSB	@segrel(S + A) */
+#define	R_IA_64_SEGREL64LSB	0x5f	/* word64 LSB	@segrel(S + A) */
+#define	R_IA_64_SECREL32MSB	0x64	/* word32 MSB	@secrel(S + A) */
+#define	R_IA_64_SECREL32LSB	0x65	/* word32 LSB	@secrel(S + A) */
+#define	R_IA_64_SECREL64MSB	0x66	/* word64 MSB	@secrel(S + A) */
+#define	R_IA_64_SECREL64LSB	0x67	/* word64 LSB	@secrel(S + A) */
+#define	R_IA_64_REL32MSB	0x6c	/* word32 MSB	BD + A */
+#define	R_IA_64_REL32LSB	0x6d	/* word32 LSB	BD + A */
+#define	R_IA_64_REL64MSB	0x6e	/* word64 MSB	BD + A */
+#define	R_IA_64_REL64LSB	0x6f	/* word64 LSB	BD + A */
+#define	R_IA_64_LTV32MSB	0x74	/* word32 MSB	S + A */
+#define	R_IA_64_LTV32LSB	0x75	/* word32 LSB	S + A */
+#define	R_IA_64_LTV64MSB	0x76	/* word64 MSB	S + A */
+#define	R_IA_64_LTV64LSB	0x77	/* word64 LSB	S + A */
+#define	R_IA_64_PCREL21BI	0x79	/* immediate21 form1 S + A - P */
+#define	R_IA_64_PCREL22		0x7a	/* immediate22	S + A - P */
+#define	R_IA_64_PCREL64I	0x7b	/* immediate64	S + A - P */
+#define	R_IA_64_IPLTMSB		0x80	/* function descriptor MSB special */
+#define	R_IA_64_IPLTLSB		0x81	/* function descriptor LSB speciaal */
+#define	R_IA_64_SUB		0x85	/* immediate64	A - S */
+#define	R_IA_64_LTOFF22X	0x86	/* immediate22	special */
+#define	R_IA_64_LDXMOV		0x87	/* immediate22	special */
+#define	R_IA_64_TPREL14		0x91	/* imm14	@tprel(S + A) */
+#define	R_IA_64_TPREL22		0x92	/* imm22	@tprel(S + A) */
+#define	R_IA_64_TPREL64I	0x93	/* imm64	@tprel(S + A) */
+#define	R_IA_64_TPREL64MSB	0x96	/* word64 MSB	@tprel(S + A) */
+#define	R_IA_64_TPREL64LSB	0x97	/* word64 LSB	@tprel(S + A) */
+#define	R_IA_64_LTOFF_TPREL22	0x9a	/* imm22	@ltoff(@tprel(S+A)) */
+#define	R_IA_64_DTPMOD64MSB	0xa6	/* word64 MSB	@dtpmod(S + A) */
+#define	R_IA_64_DTPMOD64LSB	0xa7	/* word64 LSB	@dtpmod(S + A) */
+#define	R_IA_64_LTOFF_DTPMOD22	0xaa	/* imm22	@ltoff(@dtpmod(S+A)) */
+#define	R_IA_64_DTPREL14	0xb1	/* imm14	@dtprel(S + A) */
+#define	R_IA_64_DTPREL22	0xb2	/* imm22	@dtprel(S + A) */
+#define	R_IA_64_DTPREL64I	0xb3	/* imm64	@dtprel(S + A) */
+#define	R_IA_64_DTPREL32MSB	0xb4	/* word32 MSB	@dtprel(S + A) */
+#define	R_IA_64_DTPREL32LSB	0xb5	/* word32 LSB	@dtprel(S + A) */
+#define	R_IA_64_DTPREL64MSB	0xb6	/* word64 MSB	@dtprel(S + A) */
+#define	R_IA_64_DTPREL64LSB	0xb7	/* word64 LSB	@dtprel(S + A) */
+#define	R_IA_64_LTOFF_DTPREL22	0xba	/* imm22	@ltoff(@dtprel(S+A)) */
+
+#define	R_MIPS_NONE	0	/* No reloc */
+#define	R_MIPS_16	1	/* Direct 16 bit */
+#define	R_MIPS_32	2	/* Direct 32 bit */
+#define	R_MIPS_REL32	3	/* PC relative 32 bit */
+#define	R_MIPS_26	4	/* Direct 26 bit shifted */
+#define	R_MIPS_HI16	5	/* High 16 bit */
+#define	R_MIPS_LO16	6	/* Low 16 bit */
+#define	R_MIPS_GPREL16	7	/* GP relative 16 bit */
+#define	R_MIPS_LITERAL	8	/* 16 bit literal entry */
+#define	R_MIPS_GOT16	9	/* 16 bit GOT entry */
+#define	R_MIPS_PC16	10	/* PC relative 16 bit */
+#define	R_MIPS_CALL16	11	/* 16 bit GOT entry for function */
+#define	R_MIPS_GPREL32	12	/* GP relative 32 bit */
+#define	R_MIPS_64	18	/* Direct 64 bit */
+#define	R_MIPS_GOT_DISP	19
+#define	R_MIPS_GOT_PAGE	20
+#define	R_MIPS_GOT_OFST	21
+#define	R_MIPS_GOT_HI16	22	/* GOT HI 16 bit */
+#define	R_MIPS_GOT_LO16	23	/* GOT LO 16 bit */
+#define	R_MIPS_SUB	24
+#define	R_MIPS_CALLHI16 30	/* upper 16 bit GOT entry for function */
+#define	R_MIPS_CALLLO16 31	/* lower 16 bit GOT entry for function */
+#define	R_MIPS_JALR	37
+#define	R_MIPS_TLS_GD	42
+#define	R_MIPS_COPY	126
+#define	R_MIPS_JUMP_SLOT	127
+
+#define	R_PPC_NONE		0	/* No relocation. */
+#define	R_PPC_ADDR32		1
+#define	R_PPC_ADDR24		2
+#define	R_PPC_ADDR16		3
+#define	R_PPC_ADDR16_LO		4
+#define	R_PPC_ADDR16_HI		5
+#define	R_PPC_ADDR16_HA		6
+#define	R_PPC_ADDR14		7
+#define	R_PPC_ADDR14_BRTAKEN	8
+#define	R_PPC_ADDR14_BRNTAKEN	9
+#define	R_PPC_REL24		10
+#define	R_PPC_REL14		11
+#define	R_PPC_REL14_BRTAKEN	12
+#define	R_PPC_REL14_BRNTAKEN	13
+#define	R_PPC_GOT16		14
+#define	R_PPC_GOT16_LO		15
+#define	R_PPC_GOT16_HI		16
+#define	R_PPC_GOT16_HA		17
+#define	R_PPC_PLTREL24		18
+#define	R_PPC_COPY		19
+#define	R_PPC_GLOB_DAT		20
+#define	R_PPC_JMP_SLOT		21
+#define	R_PPC_RELATIVE		22
+#define	R_PPC_LOCAL24PC		23
+#define	R_PPC_UADDR32		24
+#define	R_PPC_UADDR16		25
+#define	R_PPC_REL32		26
+#define	R_PPC_PLT32		27
+#define	R_PPC_PLTREL32		28
+#define	R_PPC_PLT16_LO		29
+#define	R_PPC_PLT16_HI		30
+#define	R_PPC_PLT16_HA		31
+#define	R_PPC_SDAREL16		32
+#define	R_PPC_SECTOFF		33
+#define	R_PPC_SECTOFF_LO	34
+#define	R_PPC_SECTOFF_HI	35
+#define	R_PPC_SECTOFF_HA	36
+#define	R_PPC_IRELATIVE		248
+
+/*
+ * 64-bit relocations
+ */
+#define	R_PPC64_ADDR64		38
+#define	R_PPC64_ADDR16_HIGHER	39
+#define	R_PPC64_ADDR16_HIGHERA	40
+#define	R_PPC64_ADDR16_HIGHEST	41
+#define	R_PPC64_ADDR16_HIGHESTA	42
+#define	R_PPC64_UADDR64		43
+#define	R_PPC64_REL64		44
+#define	R_PPC64_PLT64		45
+#define	R_PPC64_PLTREL64	46
+#define	R_PPC64_TOC16		47
+#define	R_PPC64_TOC16_LO	48
+#define	R_PPC64_TOC16_HI	49
+#define	R_PPC64_TOC16_HA	50
+#define	R_PPC64_TOC		51
+#define	R_PPC64_DTPMOD64	68
+#define	R_PPC64_TPREL64		73
+#define	R_PPC64_DTPREL64	78
+
+/*
+ * TLS relocations
+ */
+#define	R_PPC_TLS		67
+#define	R_PPC_DTPMOD32		68
+#define	R_PPC_TPREL16		69
+#define	R_PPC_TPREL16_LO	70
+#define	R_PPC_TPREL16_HI	71
+#define	R_PPC_TPREL16_HA	72
+#define	R_PPC_TPREL32		73
+#define	R_PPC_DTPREL16		74
+#define	R_PPC_DTPREL16_LO	75
+#define	R_PPC_DTPREL16_HI	76
+#define	R_PPC_DTPREL16_HA	77
+#define	R_PPC_DTPREL32		78
+#define	R_PPC_GOT_TLSGD16	79
+#define	R_PPC_GOT_TLSGD16_LO	80
+#define	R_PPC_GOT_TLSGD16_HI	81
+#define	R_PPC_GOT_TLSGD16_HA	82
+#define	R_PPC_GOT_TLSLD16	83
+#define	R_PPC_GOT_TLSLD16_LO	84
+#define	R_PPC_GOT_TLSLD16_HI	85
+#define	R_PPC_GOT_TLSLD16_HA	86
+#define	R_PPC_GOT_TPREL16	87
+#define	R_PPC_GOT_TPREL16_LO	88
+#define	R_PPC_GOT_TPREL16_HI	89
+#define	R_PPC_GOT_TPREL16_HA	90
+
+/*
+ * The remaining relocs are from the Embedded ELF ABI, and are not in the
+ *  SVR4 ELF ABI.
+ */
+
+#define	R_PPC_EMB_NADDR32	101
+#define	R_PPC_EMB_NADDR16	102
+#define	R_PPC_EMB_NADDR16_LO	103
+#define	R_PPC_EMB_NADDR16_HI	104
+#define	R_PPC_EMB_NADDR16_HA	105
+#define	R_PPC_EMB_SDAI16	106
+#define	R_PPC_EMB_SDA2I16	107
+#define	R_PPC_EMB_SDA2REL	108
+#define	R_PPC_EMB_SDA21		109
+#define	R_PPC_EMB_MRKREF	110
+#define	R_PPC_EMB_RELSEC16	111
+#define	R_PPC_EMB_RELST_LO	112
+#define	R_PPC_EMB_RELST_HI	113
+#define	R_PPC_EMB_RELST_HA	114
+#define	R_PPC_EMB_BIT_FLD	115
+#define	R_PPC_EMB_RELSDA	116
+
+/*
+ * RISC-V relocation types.
+ */
+
+/* Relocation types used by the dynamic linker. */
+#define	R_RISCV_NONE		0
+#define	R_RISCV_32		1
+#define	R_RISCV_64		2
+#define	R_RISCV_RELATIVE	3
+#define	R_RISCV_COPY		4
+#define	R_RISCV_JUMP_SLOT	5
+#define	R_RISCV_TLS_DTPMOD32	6
+#define	R_RISCV_TLS_DTPMOD64	7
+#define	R_RISCV_TLS_DTPREL32	8
+#define	R_RISCV_TLS_DTPREL64	9
+#define	R_RISCV_TLS_TPREL32	10
+#define	R_RISCV_TLS_TPREL64	11
+
+/* Relocation types not used by the dynamic linker. */
+#define	R_RISCV_BRANCH		16
+#define	R_RISCV_JAL		17
+#define	R_RISCV_CALL		18
+#define	R_RISCV_CALL_PLT	19
+#define	R_RISCV_GOT_HI20	20
+#define	R_RISCV_TLS_GOT_HI20	21
+#define	R_RISCV_TLS_GD_HI20	22
+#define	R_RISCV_PCREL_HI20	23
+#define	R_RISCV_PCREL_LO12_I	24
+#define	R_RISCV_PCREL_LO12_S	25
+#define	R_RISCV_HI20		26
+#define	R_RISCV_LO12_I		27
+#define	R_RISCV_LO12_S		28
+#define	R_RISCV_TPREL_HI20	29
+#define	R_RISCV_TPREL_LO12_I	30
+#define	R_RISCV_TPREL_LO12_S	31
+#define	R_RISCV_TPREL_ADD	32
+#define	R_RISCV_ADD8		33
+#define	R_RISCV_ADD16		34
+#define	R_RISCV_ADD32		35
+#define	R_RISCV_ADD64		36
+#define	R_RISCV_SUB8		37
+#define	R_RISCV_SUB16		38
+#define	R_RISCV_SUB32		39
+#define	R_RISCV_SUB64		40
+#define	R_RISCV_GNU_VTINHERIT	41
+#define	R_RISCV_GNU_VTENTRY	42
+#define	R_RISCV_ALIGN		43
+#define	R_RISCV_RVC_BRANCH	44
+#define	R_RISCV_RVC_JUMP	45
+#define	R_RISCV_RVC_LUI		46
+#define	R_RISCV_RELAX		51
+#define	R_RISCV_SUB6		52
+#define	R_RISCV_SET6		53
+#define	R_RISCV_SET8		54
+#define	R_RISCV_SET16		55
+#define	R_RISCV_SET32		56
+#define	R_RISCV_32_PCREL	57
+#define	R_RISCV_IRELATIVE	58
+
+#define	R_SPARC_NONE		0
+#define	R_SPARC_8		1
+#define	R_SPARC_16		2
+#define	R_SPARC_32		3
+#define	R_SPARC_DISP8		4
+#define	R_SPARC_DISP16		5
+#define	R_SPARC_DISP32		6
+#define	R_SPARC_WDISP30		7
+#define	R_SPARC_WDISP22		8
+#define	R_SPARC_HI22		9
+#define	R_SPARC_22		10
+#define	R_SPARC_13		11
+#define	R_SPARC_LO10		12
+#define	R_SPARC_GOT10		13
+#define	R_SPARC_GOT13		14
+#define	R_SPARC_GOT22		15
+#define	R_SPARC_PC10		16
+#define	R_SPARC_PC22		17
+#define	R_SPARC_WPLT30		18
+#define	R_SPARC_COPY		19
+#define	R_SPARC_GLOB_DAT	20
+#define	R_SPARC_JMP_SLOT	21
+#define	R_SPARC_RELATIVE	22
+#define	R_SPARC_UA32		23
+#define	R_SPARC_PLT32		24
+#define	R_SPARC_HIPLT22		25
+#define	R_SPARC_LOPLT10		26
+#define	R_SPARC_PCPLT32		27
+#define	R_SPARC_PCPLT22		28
+#define	R_SPARC_PCPLT10		29
+#define	R_SPARC_10		30
+#define	R_SPARC_11		31
+#define	R_SPARC_64		32
+#define	R_SPARC_OLO10		33
+#define	R_SPARC_HH22		34
+#define	R_SPARC_HM10		35
+#define	R_SPARC_LM22		36
+#define	R_SPARC_PC_HH22		37
+#define	R_SPARC_PC_HM10		38
+#define	R_SPARC_PC_LM22		39
+#define	R_SPARC_WDISP16		40
+#define	R_SPARC_WDISP19		41
+#define	R_SPARC_GLOB_JMP	42
+#define	R_SPARC_7		43
+#define	R_SPARC_5		44
+#define	R_SPARC_6		45
+#define	R_SPARC_DISP64		46
+#define	R_SPARC_PLT64		47
+#define	R_SPARC_HIX22		48
+#define	R_SPARC_LOX10		49
+#define	R_SPARC_H44		50
+#define	R_SPARC_M44		51
+#define	R_SPARC_L44		52
+#define	R_SPARC_REGISTER	53
+#define	R_SPARC_UA64		54
+#define	R_SPARC_UA16		55
+#define	R_SPARC_TLS_GD_HI22	56
+#define	R_SPARC_TLS_GD_LO10	57
+#define	R_SPARC_TLS_GD_ADD	58
+#define	R_SPARC_TLS_GD_CALL	59
+#define	R_SPARC_TLS_LDM_HI22	60
+#define	R_SPARC_TLS_LDM_LO10	61
+#define	R_SPARC_TLS_LDM_ADD	62
+#define	R_SPARC_TLS_LDM_CALL	63
+#define	R_SPARC_TLS_LDO_HIX22	64
+#define	R_SPARC_TLS_LDO_LOX10	65
+#define	R_SPARC_TLS_LDO_ADD	66
+#define	R_SPARC_TLS_IE_HI22	67
+#define	R_SPARC_TLS_IE_LO10	68
+#define	R_SPARC_TLS_IE_LD	69
+#define	R_SPARC_TLS_IE_LDX	70
+#define	R_SPARC_TLS_IE_ADD	71
+#define	R_SPARC_TLS_LE_HIX22	72
+#define	R_SPARC_TLS_LE_LOX10	73
+#define	R_SPARC_TLS_DTPMOD32	74
+#define	R_SPARC_TLS_DTPMOD64	75
+#define	R_SPARC_TLS_DTPOFF32	76
+#define	R_SPARC_TLS_DTPOFF64	77
+#define	R_SPARC_TLS_TPOFF32	78
+#define	R_SPARC_TLS_TPOFF64	79
+
+#define	R_X86_64_NONE		0	/* No relocation. */
+#define	R_X86_64_64		1	/* Add 64 bit symbol value. */
+#define	R_X86_64_PC32		2	/* PC-relative 32 bit signed sym value. */
+#define	R_X86_64_GOT32		3	/* PC-relative 32 bit GOT offset. */
+#define	R_X86_64_PLT32		4	/* PC-relative 32 bit PLT offset. */
+#define	R_X86_64_COPY		5	/* Copy data from shared object. */
+#define	R_X86_64_GLOB_DAT	6	/* Set GOT entry to data address. */
+#define	R_X86_64_JMP_SLOT	7	/* Set GOT entry to code address. */
+#define	R_X86_64_RELATIVE	8	/* Add load address of shared object. */
+#define	R_X86_64_GOTPCREL	9	/* Add 32 bit signed pcrel offset to GOT. */
+#define	R_X86_64_32		10	/* Add 32 bit zero extended symbol value */
+#define	R_X86_64_32S		11	/* Add 32 bit sign extended symbol value */
+#define	R_X86_64_16		12	/* Add 16 bit zero extended symbol value */
+#define	R_X86_64_PC16		13	/* Add 16 bit signed extended pc relative symbol value */
+#define	R_X86_64_8		14	/* Add 8 bit zero extended symbol value */
+#define	R_X86_64_PC8		15	/* Add 8 bit signed extended pc relative symbol value */
+#define	R_X86_64_DTPMOD64	16	/* ID of module containing symbol */
+#define	R_X86_64_DTPOFF64	17	/* Offset in TLS block */
+#define	R_X86_64_TPOFF64	18	/* Offset in static TLS block */
+#define	R_X86_64_TLSGD		19	/* PC relative offset to GD GOT entry */
+#define	R_X86_64_TLSLD		20	/* PC relative offset to LD GOT entry */
+#define	R_X86_64_DTPOFF32	21	/* Offset in TLS block */
+#define	R_X86_64_GOTTPOFF	22	/* PC relative offset to IE GOT entry */
+#define	R_X86_64_TPOFF32	23	/* Offset in static TLS block */
+#define	R_X86_64_PC64		24	/* PC-relative 64 bit signed sym value. */
+#define	R_X86_64_GOTOFF64	25
+#define	R_X86_64_GOTPC32	26
+#define	R_X86_64_GOT64		27
+#define	R_X86_64_GOTPCREL64	28
+#define	R_X86_64_GOTPC64	29
+#define	R_X86_64_GOTPLT64	30
+#define	R_X86_64_PLTOFF64	31
+#define	R_X86_64_SIZE32		32
+#define	R_X86_64_SIZE64		33
+#define	R_X86_64_GOTPC32_TLSDESC 34
+#define	R_X86_64_TLSDESC_CALL	35
+#define	R_X86_64_TLSDESC	36
+#define	R_X86_64_IRELATIVE	37
+#define	R_X86_64_RELATIVE64	38
+/* 39 and 40 were BND-related, already decomissioned */
+#define	R_X86_64_GOTPCRELX	41
+#define	R_X86_64_REX_GOTPCRELX	42
+
+#define	ELF_BSDF_SIGFASTBLK	0x0001	/* Kernel supports fast sigblock */
+#define	ELF_BSDF_VMNOOVERCOMMIT	0x0002
+
+#endif /* !_SYS_ELF_COMMON_H_ */
diff --git a/libc/include/bits/elf_x86.h b/libc/include/bits/elf_x86.h
deleted file mode 100644
index dfbaba0..0000000
--- a/libc/include/bits/elf_x86.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*	$NetBSD: elf_machdep.h,v 1.12 2016/02/02 20:16:59 christos Exp $	*/
-
-#ifndef _X86_ELF_MACHDEP_H_
-#define _X86_ELF_MACHDEP_H_
-
-/* i386 relocations */
-#define	R_386_NONE	0
-#define	R_386_32	1
-#define	R_386_PC32	2
-#define	R_386_GOT32	3
-#define	R_386_PLT32	4
-#define	R_386_COPY	5
-#define	R_386_GLOB_DAT	6
-#define	R_386_JMP_SLOT	7
-#define	R_386_RELATIVE	8
-#define	R_386_GOTOFF	9
-#define	R_386_GOTPC	10
-#define	R_386_32PLT	11
-
-/* TLS relocations */
-#define	R_386_TLS_TPOFF	14
-#define	R_386_TLS_IE	15
-#define	R_386_TLS_GOTIE	16
-#define	R_386_TLS_LE	17
-#define	R_386_TLS_GD	18
-#define	R_386_TLS_LDM	19
-
-/* The following relocations are GNU extensions. */
-#define	R_386_16	20
-#define	R_386_PC16	21
-#define	R_386_8		22
-#define	R_386_PC8	23
-
-/* More TLS relocations */
-#define	R_386_TLS_GD_32		24
-#define	R_386_TLS_GD_PUSH	25
-#define	R_386_TLS_GD_CALL	26
-#define	R_386_TLS_GD_POP	27
-#define	R_386_TLS_LDM_32	28
-#define	R_386_TLS_LDM_PUSH	29
-#define	R_386_TLS_LDM_CALL	30
-#define	R_386_TLS_LDM_POP	31
-#define	R_386_TLS_LDO_32	32
-#define	R_386_TLS_IE_32		33
-#define	R_386_TLS_LE_32		34
-#define	R_386_TLS_DTPMOD32	35
-#define	R_386_TLS_DTPOFF32	36
-#define	R_386_TLS_TPOFF32	37
-
-#define R_386_SIZE32		38
-
-/* More TLS relocations */
-#define	R_386_TLS_GOTDESC	39
-#define	R_386_TLS_DESC_CALL	40
-#define	R_386_TLS_DESC		41
-
-#define R_386_IRELATIVE		42
-#define R_386_GOT32X		43
-
-#endif
diff --git a/libc/include/bits/elf_x86_64.h b/libc/include/bits/elf_x86_64.h
deleted file mode 100644
index 30062af..0000000
--- a/libc/include/bits/elf_x86_64.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*	$NetBSD: elf_machdep.h,v 1.5 2016/02/02 20:13:59 christos Exp $	*/
-
-#ifndef _X86_64_ELF_MACHDEP_H_
-#define _X86_64_ELF_MACHDEP_H_
-
-/* x86-64 relocations */
-
-#define R_X86_64_NONE		0
-#define R_X86_64_64		1
-#define R_X86_64_PC32		2
-#define R_X86_64_GOT32		3
-#define R_X86_64_PLT32		4
-#define R_X86_64_COPY		5
-#define R_X86_64_GLOB_DAT	6
-#define R_X86_64_JUMP_SLOT	7
-#define R_X86_64_RELATIVE	8
-#define R_X86_64_GOTPCREL	9
-#define R_X86_64_32		10
-#define R_X86_64_32S		11
-#define R_X86_64_16		12
-#define R_X86_64_PC16		13
-#define R_X86_64_8		14
-#define R_X86_64_PC8		15
-
-/* TLS relocations */
-#define R_X86_64_DTPMOD64	16
-#define R_X86_64_DTPOFF64	17
-#define R_X86_64_TPOFF64	18
-#define R_X86_64_TLSGD		19
-#define R_X86_64_TLSLD		20
-#define R_X86_64_DTPOFF32	21
-#define R_X86_64_GOTTPOFF	22
-#define R_X86_64_TPOFF32	23
-
-#define R_X86_64_PC64		24
-#define R_X86_64_GOTOFF64	25
-#define R_X86_64_GOTPC32	26
-#define R_X86_64_GOT64		27
-#define R_X86_64_GOTPCREL64	28
-#define R_X86_64_GOTPC64	29
-#define R_X86_64_GOTPLT64	30
-#define R_X86_64_PLTOFF64	31
-#define R_X86_64_SIZE32		32
-#define R_X86_64_SIZE64		33
-#define R_X86_64_GOTPC32_TLSDESC 34
-#define R_X86_64_TLSDESC_CALL	35
-#define R_X86_64_TLSDESC	36
-#define R_X86_64_IRELATIVE	37
-#define R_X86_64_RELATIVE64	38
-#define R_X86_64_PC32_BND	39
-#define R_X86_64_PLT32_BND	40
-#define R_X86_64_GOTPCRELX	41
-#define R_X86_64_REX_GOTPCRELX	42
-
-#endif
diff --git a/libc/include/bits/fenv_riscv64.h b/libc/include/bits/fenv_riscv64.h
new file mode 100644
index 0000000..e1e43b6
--- /dev/null
+++ b/libc/include/bits/fenv_riscv64.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <sys/types.h>
+
+__BEGIN_DECLS
+
+typedef __uint32_t fenv_t;
+typedef __uint32_t fexcept_t;
+
+/* Exception flags. No FE_DENORMAL for riscv64. */
+#define FE_INEXACT    0x01
+#define FE_UNDERFLOW  0x02
+#define FE_OVERFLOW   0x04
+#define FE_DIVBYZERO  0x08
+#define FE_INVALID    0x10
+#define FE_ALL_EXCEPT (FE_DIVBYZERO | FE_INEXACT | FE_INVALID | FE_OVERFLOW | FE_UNDERFLOW)
+
+/* Rounding modes. */
+#define FE_TONEAREST  0x0
+#define FE_TOWARDZERO 0x1
+#define FE_DOWNWARD   0x2
+#define FE_UPWARD     0x3
+
+__END_DECLS
diff --git a/libc/include/elf.h b/libc/include/elf.h
index 536b8c3..1dfc008 100644
--- a/libc/include/elf.h
+++ b/libc/include/elf.h
@@ -30,13 +30,12 @@
 
 #include <sys/cdefs.h>
 
-#include <bits/auxvec.h>
-#include <bits/elf_arm.h>
-#include <bits/elf_arm64.h>
-#include <bits/elf_x86.h>
-#include <bits/elf_x86_64.h>
 #include <linux/elf.h>
 #include <linux/elf-em.h>
+#undef EI_PAD
+
+#include <bits/auxvec.h>
+#include <bits/elf_common.h>
 
 /* http://www.sco.com/developers/gabi/latest/ch4.intro.html */
 typedef __u64 Elf32_Xword;
@@ -83,14 +82,6 @@
   Elf64_Word l_version;
   Elf64_Word l_flags;
 } Elf64_Lib;
-/* ElfW(Lib)::l_flags values. */
-#define LL_NONE 0x0
-#define LL_EXACT_MATCH 0x1
-#define LL_IGNORE_INT_VER 0x2
-#define LL_REQUIRE_MINOR 0x4
-#define LL_EXPORTS 0x8
-#define LL_DELAY_LOAD 0x10
-#define LL_DELTA 0x20
 
 typedef struct {
   Elf32_Xword m_value;
@@ -118,14 +109,6 @@
   Elf64_Half si_boundto;
   Elf64_Half si_flags;
 } Elf64_Syminfo;
-/* ElfW(Syminfo)::si_boundto values. */
-#define SYMINFO_BT_SELF 0xffff
-#define SYMINFO_BT_PARENT 0xfffe
-/* ElfW(Syminfo)::si_flags values. */
-#define SYMINFO_FLG_DIRECT 0x1
-#define SYMINFO_FLG_PASSTHRU 0x2
-#define SYMINFO_FLG_COPY 0x4
-#define SYMINFO_FLG_LAZYLOAD 0x8
 
 typedef Elf32_Half Elf32_Versym;
 typedef Elf64_Half Elf64_Versym;
@@ -197,24 +180,12 @@
 typedef Elf64_Xword Elf64_Relr;
 
 /* http://www.sco.com/developers/gabi/latest/ch5.dynamic.html */
-#define DF_ORIGIN     0x00000001
-#define DF_SYMBOLIC   0x00000002
-#define DF_TEXTREL    0x00000004
-#define DF_BIND_NOW   0x00000008
-#define DF_STATIC_TLS 0x00000010
 
 #define DF_1_NOW        0x00000001 /* Perform complete relocation processing. */
-#define DF_1_GLOBAL     0x00000002 /* implies RTLD_GLOBAL */
 #define DF_1_GROUP      0x00000004
-#define DF_1_NODELETE   0x00000008 /* implies RTLD_NODELETE */
-#define DF_1_LOADFLTR   0x00000010
 #define DF_1_INITFIRST  0x00000020
-#define DF_1_NOOPEN     0x00000040 /* Object can not be used with dlopen(3) */
-#define DF_1_ORIGIN     0x00000080
 #define DF_1_DIRECT     0x00000100
 #define DF_1_TRANS      0x00000200
-#define DF_1_INTERPOSE  0x00000400
-#define DF_1_NODEFLIB   0x00000800
 #define DF_1_NODUMP     0x00001000 /* Object cannot be dumped with dldump(3) */
 #define DF_1_CONFALT    0x00002000
 #define DF_1_ENDFILTEE  0x00004000
@@ -230,58 +201,10 @@
 #define DF_1_GLOBAUDIT  0x01000000
 #define DF_1_SINGLETON  0x02000000
 #define DF_1_STUB       0x04000000
-#define DF_1_PIE        0x08000000
-
-/* http://www.sco.com/developers/gabi/latest/ch5.dynamic.html */
-#define DT_BIND_NOW 24
-#define DT_INIT_ARRAY 25
-#define DT_FINI_ARRAY 26
-#define DT_INIT_ARRAYSZ 27
-#define DT_FINI_ARRAYSZ 28
-#define DT_RUNPATH 29
-#define DT_FLAGS 30
-/* glibc and BSD disagree for DT_ENCODING; glibc looks wrong. */
-#define DT_PREINIT_ARRAY 32
-#define DT_PREINIT_ARRAYSZ 33
-#define DT_RELRSZ 35
-#define DT_RELR 36
-#define DT_RELRENT 37
-
-#define DT_GNU_HASH 0x6ffffef5
-#define DT_TLSDESC_PLT 0x6ffffef6
-#define DT_TLSDESC_GOT 0x6ffffef7
-
-/* http://www.sco.com/developers/gabi/latest/ch4.eheader.html */
-#define EI_ABIVERSION 8
-#undef EI_PAD
-#define EI_PAD 9
-
-/* http://www.sco.com/developers/gabi/latest/ch4.sheader.html */
-#define ELFCOMPRESS_ZLIB 1
-#define ELFCOMPRESS_LOOS 0x60000000
-#define ELFCOMPRESS_HIOS 0x6fffffff
-#define ELFCOMPRESS_LOPROC 0x70000000
-#define ELFCOMPRESS_HIPROC 0x7fffffff
 
 /* http://www.sco.com/developers/gabi/latest/ch4.eheader.html */
 #define ELFOSABI_SYSV 0 /* Synonym for ELFOSABI_NONE used by valgrind. */
-#define ELFOSABI_HPUX 1
-#define ELFOSABI_NETBSD 2
 #define ELFOSABI_GNU 3 /* Synonym for ELFOSABI_LINUX. */
-#define ELFOSABI_SOLARIS 6
-#define ELFOSABI_AIX 7
-#define ELFOSABI_IRIX 8
-#define ELFOSABI_FREEBSD 9
-#define ELFOSABI_TRU64 10
-#define ELFOSABI_MODESTO 11
-#define ELFOSABI_OPENBSD 12
-#define ELFOSABI_OPENVMS 13
-#define ELFOSABI_NSK 14
-#define ELFOSABI_AROS 15
-#define ELFOSABI_FENIXOS 16
-#define ELFOSABI_CLOUDABI 17
-#define ELFOSABI_OPENVOS 18
-#define ELFOSABI_ARM_AEABI 64
 
 /* http://www.sco.com/developers/gabi/latest/ch4.reloc.html */
 #define ELF32_R_INFO(sym, type) ((((Elf32_Word)sym) << 8) | ((type) & 0xff))
@@ -294,234 +217,17 @@
 #define ELF32_ST_INFO(b,t) ELF_ST_INFO(b,t)
 #define ELF64_ST_INFO(b,t) ELF_ST_INFO(b,t)
 
-/* http://www.sco.com/developers/gabi/latest/ch4.eheader.html */
-#define EM_S370 9
-#define EM_VPP500 17
-#define EM_960 19
-#define EM_V800 36
-#define EM_FR20 37
-#define EM_RH32 38
-#define EM_RCE 39
-#define EM_FAKE_ALPHA 41
-#define EM_TRICORE 44
-#define EM_ARC 45
-#define EM_H8_300H 47
-#define EM_H8S 48
-#define EM_H8_500 49
-#define EM_MIPS_X 51
-#define EM_COLDFIRE 52
-#define EM_68HC12 53
-#define EM_MMA 54
-#define EM_PCP 55
-#define EM_NCPU 56
-#define EM_NDR1 57
-#define EM_STARCORE 58
-#define EM_ME16 59
-#define EM_ST100 60
-#define EM_TINYJ 61
-#define EM_PDSP 63
-#define EM_PDP10 64
-#define EM_PDP11 65
-#define EM_FX66 66
-#define EM_ST9PLUS 67
-#define EM_ST7 68
-#define EM_68HC16 69
-#define EM_68HC11 70
-#define EM_68HC08 71
-#define EM_68HC05 72
-#define EM_SVX 73
-#define EM_ST19 74
-#define EM_VAX 75
-#define EM_JAVELIN 77
-#define EM_FIREPATH 78
-#define EM_ZSP 79
-#define EM_MMIX 80
-#define EM_HUANY 81
-#define EM_PRISM 82
-#define EM_AVR 83
-#define EM_FR30 84
-#define EM_D10V 85
-#define EM_D30V 86
-#define EM_V850 87
-#define EM_MN10200 90
-#define EM_PJ 91
-#define EM_ARC_COMPACT 93
-#define EM_XTENSA 94
-#define EM_VIDEOCORE 95
-#define EM_TMM_GPP 96
-#define EM_NS32K 97
-#define EM_TPC 98
-#define EM_SNP1K 99
-#define EM_ST200 100
-#define EM_IP2K 101
-#define EM_MAX 102
-#define EM_CR 103
-#define EM_F2MC16 104
-#define EM_MSP430 105
-#define EM_SE_C33 107
-#define EM_SEP 108
-#define EM_ARCA 109
-#define EM_UNICORE 110
-#define EM_EXCESS 111
-#define EM_DXP 112
-#define EM_CRX 114
-#define EM_XGATE 115
-#define EM_C166 116
-#define EM_M16C 117
-#define EM_DSPIC30F 118
-#define EM_CE 119
-#define EM_M32C 120
-#define EM_TSK3000 131
-#define EM_RS08 132
-#define EM_SHARC 133
-#define EM_ECOG2 134
-#define EM_SCORE7 135
-#define EM_DSP24 136
-#define EM_VIDEOCORE3 137
-#define EM_LATTICEMICO32 138
-#define EM_SE_C17 139
-#define EM_TI_C2000 141
-#define EM_TI_C5500 142
-#define EM_MMDSP_PLUS 160
-#define EM_CYPRESS_M8C 161
-#define EM_R32C 162
-#define EM_TRIMEDIA 163
-#define EM_QDSP6 164
-#define EM_8051 165
-#define EM_STXP7X 166
-#define EM_NDS32 167
-#define EM_ECOG1 168
-#define EM_ECOG1X 168
-#define EM_MAXQ30 169
-#define EM_XIMO16 170
-#define EM_MANIK 171
-#define EM_CRAYNV2 172
-#define EM_RX 173
-#define EM_METAG 174
-#define EM_MCST_ELBRUS 175
-#define EM_ECOG16 176
-#define EM_CR16 177
-#define EM_ETPU 178
-#define EM_SLE9X 179
-#define EM_L10M 180
-#define EM_K10M 181
-#define EM_AVR32 185
-#define EM_STM8 186
-#define EM_TILE64 187
-#define EM_CUDA 190
-#define EM_CLOUDSHIELD 192
-#define EM_COREA_1ST 193
-#define EM_COREA_2ND 194
-#define EM_ARC_COMPACT2 195
-#define EM_OPEN8 196
-#define EM_RL78 197
-#define EM_VIDEOCORE5 198
-#define EM_78KOR 199
-#define EM_56800EX 200
-#define EM_BA1 201
-#define EM_BA2 202
-#define EM_XCORE 203
-#define EM_MCHP_PIC 204
-#define EM_INTEL205 205
-#define EM_INTEL206 206
-#define EM_INTEL207 207
-#define EM_INTEL208 208
-#define EM_INTEL209 209
-#define EM_KM32 210
-#define EM_KMX32 211
-#define EM_KMX16 212
-#define EM_KMX8 213
-#define EM_KVARC 214
-#define EM_CDP 215
-#define EM_COGE 216
-#define EM_COOL 217
-#define EM_NORC 218
-#define EM_CSR_KALIMBA 219
-#define EM_Z80 220
-#define EM_VISIUM 221
-#define EM_FT32 222
-#define EM_MOXIE 223
-#define EM_AMDGPU 224
-#define EM_RISCV 243
-
-/* http://www.sco.com/developers/gabi/latest/ch4.eheader.html */
-#define ET_LOOS 0xfe00
-#define ET_HIOS 0xfeff
-
 /* http://www.sco.com/developers/gabi/latest/ch4.sheader.html */
-#define GRP_COMDAT 0x1
 #define GRP_MASKOS   0x0ff00000
 #define GRP_MASKPROC 0xf0000000
 
-/* http://www.sco.com/developers/gabi/latest/ch5.pheader.html */
-#define PF_X 0x1
-#define PF_W 0x2
-#define PF_R 0x4
-#define PF_MASKOS   0x0ff00000
-#define PF_MASKPROC 0xf0000000
-
-#define STB_LOOS 10
-#define STB_HIOS 12
-#define STB_LOPROC 13
-#define STB_HIPROC 15
-
 /* http://www.sco.com/developers/gabi/latest/ch4.sheader.html */
-#define SHF_MERGE 0x10
-#define SHF_STRINGS 0x20
-#define SHF_INFO_LINK 0x40
-#define SHF_LINK_ORDER 0x80
-#define SHF_OS_NONCONFORMING 0x100
-#define SHF_GROUP 0x200
-#define SHF_TLS 0x400
-#define SHF_COMPRESSED 0x800
-#define SHF_MASKOS 0x0ff00000
-#define SHF_MASKPROC 0xf0000000
-
-/* http://www.sco.com/developers/gabi/latest/ch4.sheader.html */
-#define SHN_LOOS 0xff20
-#define SHN_HIOS 0xff3f
-#define SHN_XINDEX 0xffff
-
-/* http://www.sco.com/developers/gabi/latest/ch4.sheader.html */
-#define SHT_INIT_ARRAY 14
-#define SHT_FINI_ARRAY 15
-#define SHT_PREINIT_ARRAY 16
-#define SHT_GROUP 17
-#define SHT_SYMTAB_SHNDX 18
+/*
+ * Standard replacement for SHT_ANDROID_RELR.
+ */
 #define SHT_RELR 19
 #undef SHT_NUM
 #define SHT_NUM 20
-#define SHT_LOOS 0x60000000
-#define SHT_HIOS 0x6fffffff
-
-/* http://www.sco.com/developers/gabi/latest/ch4.symtab.html */
-#define STN_UNDEF 0
-
-/* http://www.sco.com/developers/gabi/latest/ch4.symtab.html */
-#define STT_GNU_IFUNC 10
-#define STT_LOOS 10
-#define STT_HIOS 12
-#define STT_LOPROC 13
-#define STT_HIPROC 15
-
-/* http://www.sco.com/developers/gabi/latest/ch4.symtab.html */
-#define STV_DEFAULT 0
-#define STV_INTERNAL 1
-#define STV_HIDDEN 2
-#define STV_PROTECTED 3
-
-/* The kernel uses NT_PRFPREG but glibc also offers NT_FPREGSET */
-#define NT_FPREGSET NT_PRFPREG
-
-#define ELF_NOTE_GNU "GNU"
-
-#define NT_GNU_BUILD_ID 3
-
-#define VER_FLG_BASE 0x1
-#define VER_FLG_WEAK 0x2
-
-#define VER_NDX_LOCAL 0
-#define VER_NDX_GLOBAL 1
 
 /*
  * Experimental support for SHT_RELR sections. For details, see proposal
@@ -551,3 +257,13 @@
 #define DT_ANDROID_RELSZ 0x60000010 // DT_LOOS + 3
 #define DT_ANDROID_RELA 0x60000011 // DT_LOOS + 4
 #define DT_ANDROID_RELASZ 0x60000012 // DT_LOOS + 5
+
+/* Linux traditionally doesn't have the trailing 64 that BSD has on these. */
+#define R_AARCH64_TLS_DTPREL R_AARCH64_TLS_DTPREL64
+#define R_AARCH64_TLS_DTPMOD R_AARCH64_TLS_DTPMOD64
+#define R_AARCH64_TLS_TPREL R_AARCH64_TLS_TPREL64
+
+/* TODO: upstream these to FreeBSD? */
+#define R_ARM_TLS_DESC 13
+#define R_ARM_IRELATIVE 160
+#define R_X86_64_JUMP_SLOT 7
diff --git a/libc/include/fenv.h b/libc/include/fenv.h
index 7b775b6..3fd9852 100644
--- a/libc/include/fenv.h
+++ b/libc/include/fenv.h
@@ -35,6 +35,8 @@
 #include <bits/fenv_arm.h>
 #elif defined(__i386__)
 #include <bits/fenv_x86.h>
+#elif defined(__riscv)
+#include <bits/fenv_riscv64.h>
 #elif defined(__x86_64__)
 #include <bits/fenv_x86_64.h>
 #endif
diff --git a/libc/include/setjmp.h b/libc/include/setjmp.h
index c2a9544..a3de9c7 100644
--- a/libc/include/setjmp.h
+++ b/libc/include/setjmp.h
@@ -52,6 +52,8 @@
 #define _JBLEN 64
 #elif defined(__i386__)
 #define _JBLEN 10
+#elif defined(__riscv)
+#define _JBLEN 29
 #elif defined(__x86_64__)
 #define _JBLEN 11
 #endif
diff --git a/libc/include/sys/stat.h b/libc/include/sys/stat.h
index 4184f6c..623631e 100644
--- a/libc/include/sys/stat.h
+++ b/libc/include/sys/stat.h
@@ -40,7 +40,7 @@
 
 __BEGIN_DECLS
 
-#if defined(__aarch64__)
+#if defined(__aarch64__) || defined(__riscv)
 #define __STAT64_BODY \
   dev_t st_dev; \
   ino_t st_ino; \
diff --git a/libc/include/sys/ucontext.h b/libc/include/sys/ucontext.h
index 9c5801f..72b8adb 100644
--- a/libc/include/sys/ucontext.h
+++ b/libc/include/sys/ucontext.h
@@ -26,8 +26,7 @@
  * SUCH DAMAGE.
  */
 
-#ifndef _SYS_UCONTEXT_H_
-#define _SYS_UCONTEXT_H_
+#pragma once
 
 #include <sys/cdefs.h>
 
@@ -313,8 +312,66 @@
   struct _libc_fpstate __fpregs_mem;
 } ucontext_t;
 
+#elif defined(__riscv)
+
+#define NGREG 32
+
+#define REG_PC 0
+#define REG_RA 1
+#define REG_SP 2
+#define REG_TP 4
+#define REG_S0 8
+#define REG_A0 10
+
+typedef unsigned long __riscv_mc_gp_state[NGREG];
+
+typedef unsigned long greg_t;
+typedef unsigned long gregset_t[NGREG];
+typedef union __riscv_mc_fp_state fpregset_t;
+
+/* These match the kernel <asm/ptrace.h> types but with different names. */
+
+struct __riscv_mc_f_ext_state {
+  uint32_t __f[32];
+  uint32_t __fcsr;
+};
+
+struct __riscv_mc_d_ext_state {
+  uint64_t __f[32];
+  uint32_t __fcsr;
+};
+
+struct __riscv_mc_q_ext_state {
+  uint64_t __f[64] __attribute__((__aligned__(16)));
+  uint32_t __fcsr;
+  uint32_t __reserved[3];
+};
+
+union __riscv_mc_fp_state {
+  struct __riscv_mc_f_ext_state __f;
+  struct __riscv_mc_d_ext_state __d;
+  struct __riscv_mc_q_ext_state __q;
+};
+
+/* This matches the kernel <asm/sigcontext.h> but with different names. */
+
+typedef struct mcontext_t {
+  __riscv_mc_gp_state __gregs;
+  union __riscv_mc_fp_state __fpregs;
+} mcontext_t;
+
+/* This matches the kernel <asm/ucontext.h> but using mcontext_t. */
+
+typedef struct ucontext_t {
+  unsigned long uc_flags;
+  struct ucontext_t* uc_link;
+  stack_t uc_stack;
+  sigset_t uc_sigmask;
+  /* The kernel adds extra padding here to allow sigset_t to grow. */
+  char __padding[128 - sizeof(sigset_t)];
+  mcontext_t uc_mcontext;
+} ucontext_t;
+
 #endif
 
 __END_DECLS
-
-#endif /* _SYS_UCONTEXT_H_ */
diff --git a/libc/include/sys/user.h b/libc/include/sys/user.h
index 2392edd..432c7cb 100644
--- a/libc/include/sys/user.h
+++ b/libc/include/sys/user.h
@@ -26,8 +26,7 @@
  * SUCH DAMAGE.
  */
 
-#ifndef _SYS_USER_H_
-#define _SYS_USER_H_
+#pragma once
 
 #include <sys/cdefs.h>
 #include <stddef.h> /* For size_t. */
@@ -233,6 +232,11 @@
   uint32_t fpcr;
 };
 
+#elif defined(__riscv)
+
+// This space deliberately left blank for now.
+// No other libcs have any riscv64-specific structs.
+
 #else
 
 #error "Unsupported architecture."
@@ -240,5 +244,3 @@
 #endif
 
 __END_DECLS
-
-#endif  /* _SYS_USER_H_ */
diff --git a/libc/kernel/tools/cpp.py b/libc/kernel/tools/cpp.py
index 1496231..40e1f26 100755
--- a/libc/kernel/tools/cpp.py
+++ b/libc/kernel/tools/cpp.py
@@ -14,7 +14,7 @@
     utils.panic('ANDROID_BUILD_TOP not set.\n')
 
 # Set up the env vars for libclang.
-site.addsitedir(os.path.join(top, 'prebuilts/clang/host/linux-x86/clang-stable/lib64/python3/site-packages/'))
+site.addsitedir(os.path.join(top, 'prebuilts/clang/host/linux-x86/clang-stable/lib/python3/site-packages/'))
 
 import clang.cindex
 from clang.cindex import conf
@@ -28,7 +28,7 @@
 
 # Set up LD_LIBRARY_PATH to include libclang.so, libLLVM.so, and etc.
 # Note that setting LD_LIBRARY_PATH with os.putenv() sometimes doesn't help.
-clang.cindex.Config.set_library_file(os.path.join(top, 'prebuilts/clang/host/linux-x86/clang-stable/lib64/libclang.so'))
+clang.cindex.Config.set_library_file(os.path.join(top, 'prebuilts/clang/host/linux-x86/clang-stable/lib/libclang.so'))
 
 from defaults import *
 
diff --git a/libc/kernel/tools/defaults.py b/libc/kernel/tools/defaults.py
index 6ad0a32..abb8f82 100644
--- a/libc/kernel/tools/defaults.py
+++ b/libc/kernel/tools/defaults.py
@@ -55,12 +55,11 @@
 # but just generates cleaner results
 kernel_remove_config_macros = True
 
-# maps an architecture to a set of default macros that would be provided by
-# toolchain preprocessor
+# Maps an architecture to a set of default macros that would be provided by
+# the toolchain's preprocessor. Currently only used to remove confusing
+# big-endian junk from the 32-bit arm headers.
 kernel_default_arch_macros = {
     "arm": {"__ARMEB__": kCppUndefinedMacro, "__ARM_EABI__": "1"},
-    "arm64": {},
-    "x86": {},
     }
 
 # Replace tokens in the output according to this mapping.
diff --git a/libc/kernel/uapi/BUILD b/libc/kernel/uapi/BUILD
index 2f92464..3c9bb69 100644
--- a/libc/kernel/uapi/BUILD
+++ b/libc/kernel/uapi/BUILD
@@ -29,39 +29,39 @@
 package(default_visibility = ["//bionic/libc:__pkg__"])
 
 cc_api_headers(
-  name="libc_kernel_uapi_headers",
-  hdrs=glob(["**/*.h"]),
-  system=True,
+    name = "libc_kernel_uapi_headers",
+    hdrs = glob(["**/*.h"]),
+    system = True,
 )
 
 cc_api_headers(
-  name="libc_kernal_uapi_asm_arm_headers",
-  include_dir="asm-arm",
-  hdrs=glob(["asm-arm/**/*.h"]),
-  system=True,
-  arch="arm",
+    name = "libc_kernel_uapi_asm_arm_headers",
+    hdrs = glob(["asm-arm/**/*.h"]),
+    arch = "arm",
+    include_dir = "asm-arm",
+    system = True,
 )
 
 cc_api_headers(
-  name="libc_kernal_uapi_asm_arm64_headers",
-  include_dir="asm-arm64",
-  hdrs=glob(["asm-arm64/**/*.h"]),
-  system=True,
-  arch="arm64",
+    name = "libc_kernel_uapi_asm_arm64_headers",
+    hdrs = glob(["asm-arm64/**/*.h"]),
+    arch = "arm64",
+    include_dir = "asm-arm64",
+    system = True,
 )
 
 cc_api_headers(
-  name="libc_kernal_uapi_asm_x86_headers",
-  include_dir="asm-x86",
-  hdrs=glob(["asm-x86/**/*.h"]),
-  system=True,
-  arch="x86",
+    name = "libc_kernel_uapi_asm_x86_headers",
+    hdrs = glob(["asm-x86/**/*.h"]),
+    arch = "x86",
+    include_dir = "asm-x86",
+    system = True,
 )
 
 cc_api_headers(
-  name="libc_kernal_uapi_asm_x86_64_headers",
-  include_dir="asm-x86_64",
-  hdrs=glob(["asm-x86_64/**/*.h"]),
-  system=True,
-  arch="x86_64",
+    name = "libc_kernel_uapi_asm_x86_64_headers",
+    hdrs = glob(["asm-x86_64/**/*.h"]),
+    arch = "x86_64",
+    include_dir = "asm-x86_64",
+    system = True,
 )
diff --git a/libc/libc.map.txt b/libc/libc.map.txt
index 7bcee9d..dc1b6f6 100644
--- a/libc/libc.map.txt
+++ b/libc/libc.map.txt
@@ -1449,7 +1449,7 @@
     ___tls_get_addr; # x86
     __aeabi_read_tp; # arm
     __res_randomid;
-    __tls_get_addr; # arm x86_64
+    __tls_get_addr; # arm riscv64 x86_64
     android_fdsan_close_with_tag;
     android_fdsan_create_owner_tag;
     android_fdsan_exchange_owner_tag;
diff --git a/libc/platform/bionic/macros.h b/libc/platform/bionic/macros.h
index 076cff1..9e13e0d 100644
--- a/libc/platform/bionic/macros.h
+++ b/libc/platform/bionic/macros.h
@@ -55,6 +55,8 @@
 #define BIONIC_STOP_UNWIND asm volatile(".cfi_undefined x30")
 #elif defined(__i386__)
 #define BIONIC_STOP_UNWIND asm volatile(".cfi_undefined \%eip")
+#elif defined(__riscv)
+#define BIONIC_STOP_UNWIND asm volatile(".cfi_undefined ra")
 #elif defined(__x86_64__)
 #define BIONIC_STOP_UNWIND asm volatile(".cfi_undefined \%rip")
 #endif
diff --git a/libc/platform/bionic/tls.h b/libc/platform/bionic/tls.h
index bf9e65b..e01eccd 100644
--- a/libc/platform/bionic/tls.h
+++ b/libc/platform/bionic/tls.h
@@ -34,6 +34,8 @@
 # define __get_tls() ({ void** __val; __asm__("mrc p15, 0, %0, c13, c0, 3" : "=r"(__val)); __val; })
 #elif defined(__i386__)
 # define __get_tls() ({ void** __val; __asm__("movl %%gs:0, %0" : "=r"(__val)); __val; })
+#elif defined(__riscv)
+# define __get_tls() ({ void** __val; __asm__("mv %0, tp" : "=r"(__val)); __val; })
 #elif defined(__x86_64__)
 # define __get_tls() ({ void** __val; __asm__("mov %%fs:0, %0" : "=r"(__val)); __val; })
 #else
diff --git a/libc/platform/bionic/tls_defines.h b/libc/platform/bionic/tls_defines.h
index 78099b3..3e2efa3 100644
--- a/libc/platform/bionic/tls_defines.h
+++ b/libc/platform/bionic/tls_defines.h
@@ -114,6 +114,28 @@
 #define TLS_SLOT_BIONIC_TLS       9
 #define MAX_TLS_SLOT              9 // update this value when reserving a slot
 
+#elif defined(__riscv)
+
+// RISC-V ELF Specification[1] specifies that RISC-V uses Variant I as described
+// by the ELF TLS specification, with tp containing the address one past the end
+// of the TCB.
+//
+// [1]: RISC-V ELF Specification. Section: Thread Local Storage
+// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/master/riscv-elf.adoc#thread-local-storage
+
+#define MIN_TLS_SLOT             (-9) // update this value when reserving a slot
+
+#define TLS_SLOT_BIONIC_TLS      (-9)
+#define TLS_SLOT_DTV             (-8)
+#define TLS_SLOT_THREAD_ID       (-7)
+#define TLS_SLOT_APP             (-6)
+#define TLS_SLOT_OPENGL          (-5)
+#define TLS_SLOT_OPENGL_API      (-4)
+#define TLS_SLOT_STACK_GUARD     (-3)
+#define TLS_SLOT_SANITIZER       (-2)
+#define TLS_SLOT_ART_THREAD_SELF (-1)
+#define MAX_TLS_SLOT             (-1)
+
 #endif
 
 #define BIONIC_TLS_SLOTS (MAX_TLS_SLOT - MIN_TLS_SLOT + 1)
diff --git a/libc/private/bionic_asm.h b/libc/private/bionic_asm.h
index d68a2d6..78e5046 100644
--- a/libc/private/bionic_asm.h
+++ b/libc/private/bionic_asm.h
@@ -45,6 +45,8 @@
 #include <private/bionic_asm_arm.h>
 #elif defined(__i386__)
 #include <private/bionic_asm_x86.h>
+#elif defined(__riscv)
+#include <private/bionic_asm_riscv64.h>
 #elif defined(__x86_64__)
 #include <private/bionic_asm_x86_64.h>
 #endif
diff --git a/libc/private/bionic_asm_riscv64.h b/libc/private/bionic_asm_riscv64.h
new file mode 100644
index 0000000..463ca31
--- /dev/null
+++ b/libc/private/bionic_asm_riscv64.h
@@ -0,0 +1,43 @@
+/*	$OpenBSD: asm.h,v 1.1 2004/02/01 05:09:49 drahn Exp $	*/
+/*	$NetBSD: asm.h,v 1.4 2001/07/16 05:43:32 matt Exp $	*/
+
+/*
+ * Copyright (c) 1990 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * William Jolitz.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ *	from: @(#)asm.h	5.5 (Berkeley) 5/7/91
+ */
+
+#pragma once
+
+#define __bionic_asm_align 16
+
+#undef __bionic_asm_function_type
+#define __bionic_asm_function_type %function
diff --git a/libc/private/bionic_elf_tls.h b/libc/private/bionic_elf_tls.h
index e0ec7b5..79ffcc4 100644
--- a/libc/private/bionic_elf_tls.h
+++ b/libc/private/bionic_elf_tls.h
@@ -201,3 +201,18 @@
 struct bionic_tcb;
 void __free_dynamic_tls(bionic_tcb* tcb);
 void __notify_thread_exit_callbacks();
+
+#if defined(__riscv)
+// TLS_DTV_OFFSET is a constant used in relocation fields, defined in RISC-V ELF Specification[1]
+// The front of the TCB contains a pointer to the DTV, and each pointer in DTV
+// points to 0x800 past the start of a TLS block to make full use of the range
+// of load/store instructions, refer to [2].
+//
+// [1]: RISC-V ELF Specification.
+// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/master/riscv-elf.adoc#constants
+// [2]: Documentation of TLS data structures
+// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/issues/53
+#define TLS_DTV_OFFSET 0x800
+#else
+#define TLS_DTV_OFFSET 0
+#endif
diff --git a/libc/seccomp/seccomp_bpfs.h b/libc/seccomp/seccomp_bpfs.h
index 3bdffa9..34219e2 100644
--- a/libc/seccomp/seccomp_bpfs.h
+++ b/libc/seccomp/seccomp_bpfs.h
@@ -33,6 +33,13 @@
 extern const struct sock_filter arm64_system_filter[];
 extern const size_t arm64_system_filter_size;
 
+extern const struct sock_filter riscv64_app_filter[];
+extern const size_t riscv64_app_filter_size;
+extern const struct sock_filter riscv64_app_zygote_filter[];
+extern const size_t riscv64_app_zygote_filter_size;
+extern const struct sock_filter riscv64_system_filter[];
+extern const size_t riscv64_system_filter_size;
+
 extern const struct sock_filter x86_app_filter[];
 extern const size_t x86_app_filter_size;
 extern const struct sock_filter x86_app_zygote_filter[];
diff --git a/libc/seccomp/seccomp_policy.cpp b/libc/seccomp/seccomp_policy.cpp
index a42816e..1ca4eec 100644
--- a/libc/seccomp/seccomp_policy.cpp
+++ b/libc/seccomp/seccomp_policy.cpp
@@ -25,13 +25,13 @@
 #include <vector>
 
 #include <android-base/logging.h>
+#include <android-base/macros.h>
 
 #include "func_to_syscall_nrs.h"
 #include "seccomp_bpfs.h"
 
 #if defined __arm__ || defined __aarch64__
 
-#define DUAL_ARCH
 #define PRIMARY_ARCH AUDIT_ARCH_AARCH64
 static const struct sock_filter* primary_app_filter = arm64_app_filter;
 static const size_t primary_app_filter_size = arm64_app_filter_size;
@@ -52,9 +52,9 @@
 
 static const long secondary_setresgid = __arm_setresgid;
 static const long secondary_setresuid = __arm_setresuid;
+
 #elif defined __i386__ || defined __x86_64__
 
-#define DUAL_ARCH
 #define PRIMARY_ARCH AUDIT_ARCH_X86_64
 static const struct sock_filter* primary_app_filter = x86_64_app_filter;
 static const size_t primary_app_filter_size = x86_64_app_filter_size;
@@ -75,6 +75,20 @@
 
 static const long secondary_setresgid = __x86_setresgid;
 static const long secondary_setresuid = __x86_setresuid;
+
+#elif defined(__riscv)
+
+#define PRIMARY_ARCH AUDIT_ARCH_RISCV64
+static const struct sock_filter* primary_app_filter = riscv64_app_filter;
+static const size_t primary_app_filter_size = riscv64_app_filter_size;
+static const struct sock_filter* primary_app_zygote_filter = riscv64_app_zygote_filter;
+static const size_t primary_app_zygote_filter_size = riscv64_app_zygote_filter_size;
+static const struct sock_filter* primary_system_filter = riscv64_system_filter;
+static const size_t primary_system_filter_size = riscv64_system_filter_size;
+
+static const long primary_setresgid = __riscv64_setresgid;
+static const long primary_setresuid = __riscv64_setresuid;
+
 #else
 #error No architecture was defined!
 #endif
@@ -98,7 +112,7 @@
     f.push_back(BPF_STMT(BPF_LD|BPF_W|BPF_ABS, syscall_nr));
 }
 
-#ifdef DUAL_ARCH
+#if defined(SECONDARY_ARCH)
 static bool SetValidateArchitectureJumpTarget(size_t offset, filter& f) {
     size_t jump_length = f.size() - offset - 1;
     auto u8_jump_length = (__u8) jump_length;
@@ -149,9 +163,17 @@
 // that's the only system call we need to check here. A CTS test ensures the other
 // calls will remain blocked.
 static void ValidateSetUidGid(filter& f, uint32_t uid_gid_min, uint32_t uid_gid_max, bool primary) {
+#if defined(SECONDARY_ARCH)
+    __u32 setresuid_nr = primary ? primary_setresuid : secondary_setresuid;
+    __u32 setresgid_nr = primary ? primary_setresgid : secondary_setresgid;
+#else
+    __u32 setresuid_nr = primary_setresuid;
+    __u32 setresgid_nr = primary_setresgid;
+    UNUSED(primary);
+#endif
+
     // Check setresuid(ruid, euid, sguid) fall within range
     ExamineSyscall(f);
-    __u32 setresuid_nr = primary ? primary_setresuid : secondary_setresuid;
     f.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, setresuid_nr, 0, 12));
     for (int arg = 0; arg < 3; arg++) {
         ValidateSyscallArgInRange(f, arg, uid_gid_min, uid_gid_max);
@@ -159,7 +181,6 @@
 
     // Check setresgid(rgid, egid, sgid) fall within range
     ExamineSyscall(f);
-    __u32 setresgid_nr = primary ? primary_setresgid : secondary_setresgid;
     f.push_back(BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, setresgid_nr, 0, 12));
     for (int arg = 0; arg < 3; arg++) {
         ValidateSyscallArgInRange(f, arg, uid_gid_min, uid_gid_max);
@@ -184,7 +205,7 @@
 
 bool _install_setuidgid_filter(uint32_t uid_gid_min, uint32_t uid_gid_max) {
     filter f;
-#ifdef DUAL_ARCH
+#if defined(SECONDARY_ARCH)
     // Note that for mixed 64/32 bit architectures, ValidateArchitecture inserts a
     // jump that must be changed to point to the start of the 32-bit policy
     // 32 bit syscalls will not hit the policy between here and the call to SetJump
@@ -195,7 +216,7 @@
 
     ValidateSetUidGid(f, uid_gid_min, uid_gid_max, true /* primary */);
 
-#ifdef DUAL_ARCH
+#if defined(SECONDARY_ARCH)
     if (!SetValidateArchitectureJumpTarget(offset_to_secondary_filter, f)) {
         return false;
     }
@@ -213,32 +234,43 @@
 };
 
 bool _set_seccomp_filter(FilterType type) {
-    const sock_filter *p, *s;
-    size_t p_size, s_size;
     filter f;
 
+    const sock_filter* p;
+    size_t p_size;
+#if defined(SECONDARY_ARCH)
+    const sock_filter* s;
+    size_t s_size;
+#endif
+
     switch (type) {
       case APP:
         p = primary_app_filter;
         p_size = primary_app_filter_size;
+#if defined(SECONDARY_ARCH)
         s = secondary_app_filter;
         s_size = secondary_app_filter_size;
+#endif
         break;
       case APP_ZYGOTE:
         p = primary_app_zygote_filter;
         p_size = primary_app_zygote_filter_size;
+#if defined(SECONDARY_ARCH)
         s = secondary_app_zygote_filter;
         s_size = secondary_app_zygote_filter_size;
+#endif
         break;
       case SYSTEM:
         p = primary_system_filter;
         p_size = primary_system_filter_size;
+#if defined(SECONDARY_ARCH)
         s = secondary_system_filter;
         s_size = secondary_system_filter_size;
+#endif
         break;
     }
 
-#ifdef DUAL_ARCH
+#if defined(SECONDARY_ARCH)
     // Note that for mixed 64/32 bit architectures, ValidateArchitecture inserts a
     // jump that must be changed to point to the start of the 32-bit policy
     // 32 bit syscalls will not hit the policy between here and the call to SetJump
@@ -254,7 +286,7 @@
     }
     Disallow(f);
 
-#ifdef DUAL_ARCH
+#if defined(SECONDARY_ARCH)
     if (!SetValidateArchitectureJumpTarget(offset_to_secondary_filter, f)) {
         return false;
     }
diff --git a/libc/tools/genfunctosyscallnrs.py b/libc/tools/genfunctosyscallnrs.py
index fa48844..9b8f7ee 100755
--- a/libc/tools/genfunctosyscallnrs.py
+++ b/libc/tools/genfunctosyscallnrs.py
@@ -21,12 +21,12 @@
 
 
 def gen_syscall_nrs(out_file, base_syscall_file, syscall_NRs):
-    for arch in SupportedArchitectures:
+    for arch in syscall_NRs.keys():
         base_names = load_syscall_names_from_file(base_syscall_file, arch)
 
         for func, syscall in base_names.items():
             out_file.write("#define __" + arch + "_" + func + " " +
-                           str(syscall_NRs[arch][syscall]) + ";\n")
+                           str(syscall_NRs[arch][syscall]) + "\n")
 
 
 def main():
diff --git a/libc/tools/genseccomp.py b/libc/tools/genseccomp.py
index 33bf470..8a07caf 100755
--- a/libc/tools/genseccomp.py
+++ b/libc/tools/genseccomp.py
@@ -5,9 +5,10 @@
 import operator
 import os
 import re
+import sys
 import textwrap
 
-from gensyscalls import SupportedArchitectures, SysCallsTxtParser
+from gensyscalls import SysCallsTxtParser
 
 
 BPF_JGE = "BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K, {0}, {1}, {2})"
@@ -84,42 +85,46 @@
   #    #define __(ARM_)?NR_${NAME} ${VALUE}
   #
   # Where ${VALUE} is a preprocessor expression.
+  #
+  # Newer architectures have things like this though:
+  #
+  #    #define __NR3264_fcntl 25
+  #    #define __NR_fcntl __NR3264_fcntl
+  #
+  # So we need to keep track of the __NR3264_* constants and substitute them.
 
-  constant_re = re.compile(
-      r'^\s*#define\s+([A-Za-z_][A-Za-z0-9_]+)\s+(.+)\s*$')
+  line_re = re.compile(r'^# \d+ ".*".*')
+  undef_re = re.compile(r'^#undef\s.*')
+  define_re = re.compile(r'^\s*#define\s+([A-Za-z0-9_(,)]+)(?:\s+(.+))?\s*$')
   token_re = re.compile(r'\b[A-Za-z_][A-Za-z0-9_]+\b')
   constants = {}
+  nr3264s = {}
   with open(names_path) as f:
     for line in f:
-      m = constant_re.match(line)
-      if m is None:
-        continue
-      try:
+      line = line.strip()
+      m = define_re.match(line)
+      if m:
         name = m.group(1)
-        # eval() takes care of any arithmetic that may be done
-        value = eval(token_re.sub(lambda x: str(constants[x.group(0)]),
-                                  m.group(2)))
+        value = m.group(2)
+        if name.startswith('__NR3264'):
+          nr3264s[name] = value
+        elif name.startswith('__NR_') or name.startswith('__ARM_NR_'):
+          if value in nr3264s:
+            value = nr3264s[value]
+          # eval() takes care of any arithmetic that may be done
+          value = eval(token_re.sub(lambda x: str(constants[x.group(0)]), value))
 
-        constants[name] = value
-      except:  # pylint: disable=bare-except
-        # TODO: This seems wrong.
-        # Key error doesn't seem like the error the original author was trying
-        # to catch. It looks like the intent was to catch IndexError from
-        # match.group() for non-matching lines, but that's impossible because
-        # the match object is checked and continued if not matched. What
-        # actually happens is that KeyError is thrown by constants[x.group(0)]
-        # on at least the first run because the dict is empty.
-        #
-        # It's also matching syntax errors because not all C integer literals
-        # are valid Python integer literals, e.g. 10L.
-        logging.debug('Failed to parse %s', line)
+          constants[name] = value
+      else:
+        if not line_re.match(line) and not undef_re.match(line) and line:
+          print('%s: failed to parse line `%s`' % (names_path, line))
+          sys.exit(1)
 
   syscalls = {}
   for name, value in constants.items():
-    if not name.startswith("__NR_") and not name.startswith("__ARM_NR"):
-      continue
+    # Remove the __NR_ prefix.
+    # TODO: why not __ARM_NR too?
     if name.startswith("__NR_"):
-      # Remote the __NR_ prefix
       name = name[len("__NR_"):]
     syscalls[name] = value
 
@@ -237,7 +242,7 @@
 
 def gen_policy(name_modifier, out_dir, base_syscall_file, syscall_files,
                syscall_NRs, priority_file):
-  for arch in SupportedArchitectures:
+  for arch in syscall_NRs.keys():
     base_names = load_syscall_names_from_file(base_syscall_file, arch)
     allowlist_names = set()
     blocklist_names = set()
@@ -251,11 +256,11 @@
       priorities = load_syscall_priorities_from_file(priority_file)
 
     allowed_syscalls = []
-    for name in merge_names(base_names, allowlist_names, blocklist_names):
+    for name in sorted(merge_names(base_names, allowlist_names, blocklist_names)):
       try:
         allowed_syscalls.append((name, syscall_NRs[arch][name]))
       except:
-        logging.exception("Failed to find %s in %s", name, arch)
+        logging.exception("Failed to find %s in %s (%s)", name, arch, syscall_NRs[arch])
         raise
     output = construct_bpf(allowed_syscalls, arch, name_modifier, priorities)
 
diff --git a/libc/tools/gensyscalls.py b/libc/tools/gensyscalls.py
index baaa52d..d3e6ef4 100755
--- a/libc/tools/gensyscalls.py
+++ b/libc/tools/gensyscalls.py
@@ -15,7 +15,7 @@
 import tempfile
 
 
-SupportedArchitectures = [ "arm", "arm64", "x86", "x86_64" ]
+SupportedArchitectures = [ "arm", "arm64", "riscv64", "x86", "x86_64" ]
 
 syscall_stub_header = \
 """
@@ -80,6 +80,24 @@
 
 
 #
+# RISC-V64 assembler templates for each syscall stub
+#
+
+riscv64_call = syscall_stub_header + """\
+    li      a7, %(__NR_name)s
+    ecall
+
+    li      a7, -MAX_ERRNO
+    bgtu    a0, a7, 1f
+
+    ret
+1:
+    neg     a0, a0
+    j       __set_errno_internal
+END(%(func)s)
+"""
+
+#
 # x86 assembler templates for each syscall stub
 #
 
@@ -228,6 +246,10 @@
     return arm64_call % syscall
 
 
+def riscv64_genstub(syscall):
+    return riscv64_call % syscall
+
+
 def x86_genstub(syscall):
     result     = syscall_stub_header % syscall
 
@@ -440,6 +462,9 @@
         if "arm64" in syscall:
             syscall["asm-arm64"] = add_footer(64, arm64_genstub(syscall), syscall)
 
+        if "riscv64" in syscall:
+            syscall["asm-riscv64"] = add_footer(64, riscv64_genstub(syscall), syscall)
+
         if "x86" in syscall:
             if syscall["socketcall_id"] >= 0:
                 syscall["asm-x86"] = add_footer(32, x86_genstub_socketcall(syscall), syscall)
diff --git a/libc/upstream-freebsd/lib/libc/string/bcopy.c b/libc/upstream-freebsd/lib/libc/string/bcopy.c
new file mode 100644
index 0000000..84715d0
--- /dev/null
+++ b/libc/upstream-freebsd/lib/libc/string/bcopy.c
@@ -0,0 +1,137 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1990, 1993
+ *	The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char sccsid[] = "@(#)bcopy.c	8.1 (Berkeley) 6/4/93";
+#endif /* LIBC_SCCS and not lint */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/types.h>
+
+typedef	intptr_t word;		/* "word" used for optimal copy speed */
+
+#define	wsize	sizeof(word)
+#define	wmask	(wsize - 1)
+
+/*
+ * Copy a block of memory, handling overlap.
+ * This is the routine that actually implements
+ * (the portable versions of) bcopy, memcpy, and memmove.
+ */
+#if defined(MEMCOPY) || defined(MEMMOVE)
+#include <string.h>
+
+void *
+#ifdef MEMCOPY
+memcpy
+#else
+memmove
+#endif
+(void *dst0, const void *src0, size_t length)
+#else
+#include <strings.h>
+
+void
+bcopy(const void *src0, void *dst0, size_t length)
+#endif
+{
+	char *dst = dst0;
+	const char *src = src0;
+	size_t t;
+
+	if (length == 0 || dst == src)		/* nothing to do */
+		goto done;
+
+	/*
+	 * Macros: loop-t-times; and loop-t-times, t>0
+	 */
+#define	TLOOP(s) if (t) TLOOP1(s)
+#define	TLOOP1(s) do { s; } while (--t)
+
+	if ((unsigned long)dst < (unsigned long)src) {
+		/*
+		 * Copy forward.
+		 */
+		t = (uintptr_t)src;	/* only need low bits */
+		if ((t | (uintptr_t)dst) & wmask) {
+			/*
+			 * Try to align operands.  This cannot be done
+			 * unless the low bits match.
+			 */
+			if ((t ^ (uintptr_t)dst) & wmask || length < wsize)
+				t = length;
+			else
+				t = wsize - (t & wmask);
+			length -= t;
+			TLOOP1(*dst++ = *src++);
+		}
+		/*
+		 * Copy whole words, then mop up any trailing bytes.
+		 */
+		t = length / wsize;
+		TLOOP(*(word *)(void *)dst = *(const word *)(const void *)src;
+		    src += wsize; dst += wsize);
+		t = length & wmask;
+		TLOOP(*dst++ = *src++);
+	} else {
+		/*
+		 * Copy backwards.  Otherwise essentially the same.
+		 * Alignment works as before, except that it takes
+		 * (t&wmask) bytes to align, not wsize-(t&wmask).
+		 */
+		src += length;
+		dst += length;
+		t = (uintptr_t)src;
+		if ((t | (uintptr_t)dst) & wmask) {
+			if ((t ^ (uintptr_t)dst) & wmask || length <= wsize)
+				t = length;
+			else
+				t &= wmask;
+			length -= t;
+			TLOOP1(*--dst = *--src);
+		}
+		t = length / wsize;
+		TLOOP(src -= wsize; dst -= wsize;
+		    *(word *)(void *)dst = *(const word *)(const void *)src);
+		t = length & wmask;
+		TLOOP(*--dst = *--src);
+	}
+done:
+#if defined(MEMCOPY) || defined(MEMMOVE)
+	return (dst0);
+#else
+	return;
+#endif
+}
diff --git a/libc/upstream-freebsd/lib/libc/string/memcmp.c b/libc/upstream-freebsd/lib/libc/string/memcmp.c
new file mode 100644
index 0000000..c8d5d92
--- /dev/null
+++ b/libc/upstream-freebsd/lib/libc/string/memcmp.c
@@ -0,0 +1,58 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1990, 1993
+ *	The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Chris Torek.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char sccsid[] = "@(#)memcmp.c	8.1 (Berkeley) 6/4/93";
+#endif /* LIBC_SCCS and not lint */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <string.h>
+
+/*
+ * Compare memory regions.
+ */
+int
+memcmp(const void *s1, const void *s2, size_t n)
+{
+	if (n != 0) {
+		const unsigned char *p1 = s1, *p2 = s2;
+
+		do {
+			if (*p1++ != *p2++)
+				return (*--p1 - *--p2);
+		} while (--n != 0);
+	}
+	return (0);
+}
diff --git a/libc/upstream-freebsd/lib/libc/string/memcpy.c b/libc/upstream-freebsd/lib/libc/string/memcpy.c
new file mode 100644
index 0000000..ed03856
--- /dev/null
+++ b/libc/upstream-freebsd/lib/libc/string/memcpy.c
@@ -0,0 +1,5 @@
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#define	MEMCOPY
+#include "bcopy.c"
diff --git a/libc/upstream-freebsd/lib/libc/string/memmove.c b/libc/upstream-freebsd/lib/libc/string/memmove.c
new file mode 100644
index 0000000..05cf75a
--- /dev/null
+++ b/libc/upstream-freebsd/lib/libc/string/memmove.c
@@ -0,0 +1,5 @@
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#define	MEMMOVE
+#include "bcopy.c"
diff --git a/libc/upstream-freebsd/lib/libc/string/memset.c b/libc/upstream-freebsd/lib/libc/string/memset.c
new file mode 100644
index 0000000..e2d4027
--- /dev/null
+++ b/libc/upstream-freebsd/lib/libc/string/memset.c
@@ -0,0 +1,133 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1990, 1993
+ *	The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Mike Hibler and Chris Torek.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char sccsid[] = "@(#)memset.c	8.1 (Berkeley) 6/4/93";
+#endif /* LIBC_SCCS and not lint */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/types.h>
+
+#include <limits.h>
+
+#define	wsize	sizeof(u_long)
+#define	wmask	(wsize - 1)
+
+#ifdef BZERO
+#include <strings.h>
+
+#define	RETURN	return
+#define	VAL	0
+#define	WIDEVAL	0
+
+void
+bzero(void *dst0, size_t length)
+#else
+#include <string.h>
+
+#define	RETURN	return (dst0)
+#define	VAL	c0
+#define	WIDEVAL	c
+
+void *
+memset(void *dst0, int c0, size_t length)
+#endif
+{
+	size_t t;
+#ifndef BZERO
+	u_long c;
+#endif
+	u_char *dst;
+
+	dst = dst0;
+	/*
+	 * If not enough words, just fill bytes.  A length >= 2 words
+	 * guarantees that at least one of them is `complete' after
+	 * any necessary alignment.  For instance:
+	 *
+	 *	|-----------|-----------|-----------|
+	 *	|00|01|02|03|04|05|06|07|08|09|0A|00|
+	 *	          ^---------------------^
+	 *		 dst		 dst+length-1
+	 *
+	 * but we use a minimum of 3 here since the overhead of the code
+	 * to do word writes is substantial.
+	 *
+	 * TODO: This threshold might not be sensible for 64-bit u_long.
+	 * We should benchmark and revisit this decision.
+	 */
+	if (length < 3 * wsize) {
+		while (length != 0) {
+			*dst++ = VAL;
+			--length;
+		}
+		RETURN;
+	}
+
+#ifndef BZERO
+	if ((c = (u_char)c0) != 0) {	/* Fill the word. */
+		c = (c << 8) | c;	/* u_long is 16 bits. */
+#if ULONG_MAX > 0xffff
+		c = (c << 16) | c;	/* u_long is 32 bits. */
+#endif
+#if ULONG_MAX > 0xffffffff
+		c = (c << 32) | c;	/* u_long is 64 bits. */
+#endif
+	}
+#endif
+	/* Align destination by filling in bytes. */
+	if ((t = (long)dst & wmask) != 0) {
+		t = wsize - t;
+		length -= t;
+		do {
+			*dst++ = VAL;
+		} while (--t != 0);
+	}
+
+	/* Fill words.  Length was >= 2*words so we know t >= 1 here. */
+	t = length / wsize;
+	do {
+		*(u_long *)(void *)dst = WIDEVAL;
+		dst += wsize;
+	} while (--t != 0);
+
+	/* Mop up trailing bytes, if any. */
+	t = length & wmask;
+	if (t != 0)
+		do {
+			*dst++ = VAL;
+		} while (--t != 0);
+	RETURN;
+}
diff --git a/libdl/Android.bp b/libdl/Android.bp
index 9714af5..4cdec44 100644
--- a/libdl/Android.bp
+++ b/libdl/Android.bp
@@ -74,6 +74,7 @@
         "-Wl,--exclude-libs=libclang_rt.builtins-arm-android.a",
         "-Wl,--exclude-libs=libclang_rt.builtins-aarch64-android.a",
         "-Wl,--exclude-libs=libclang_rt.builtins-i686-android.a",
+        "-Wl,--exclude-libs=libclang_rt.builtins-riscv64-android.a",
         "-Wl,--exclude-libs=libclang_rt.builtins-x86_64-android.a",
     ],
 
@@ -87,6 +88,9 @@
         arm64: {
             version_script: ":libdl.arm64.map",
         },
+        riscv64: {
+            version_script: ":libdl.riscv64.map",
+        },
         x86: {
             pack_relocations: false,
             ldflags: [
@@ -174,6 +178,7 @@
         "-Wl,--exclude-libs=libclang_rt.builtins-arm-android.a",
         "-Wl,--exclude-libs=libclang_rt.builtins-aarch64-android.a",
         "-Wl,--exclude-libs=libclang_rt.builtins-i686-android.a",
+        "-Wl,--exclude-libs=libclang_rt.builtins-riscv64-android.a",
         "-Wl,--exclude-libs=libclang_rt.builtins-x86_64-android.a",
     ],
 
@@ -254,6 +259,14 @@
 }
 
 genrule {
+    name: "libdl.riscv64.map",
+    out: ["libdl.riscv64.map"],
+    srcs: ["libdl.map.txt"],
+    tools: ["generate-version-script"],
+    cmd: "$(location generate-version-script) riscv64 $(in) $(out)",
+}
+
+genrule {
     name: "libdl.x86.map",
     out: ["libdl.x86.map"],
     srcs: ["libdl.map.txt"],
diff --git a/libm/Android.bp b/libm/Android.bp
index 641956c..8024fbe 100644
--- a/libm/Android.bp
+++ b/libm/Android.bp
@@ -73,8 +73,6 @@
         "upstream-freebsd/lib/msun/src/e_scalbf.c",
         "upstream-freebsd/lib/msun/src/e_sinh.c",
         "upstream-freebsd/lib/msun/src/e_sinhf.c",
-        "upstream-freebsd/lib/msun/src/e_sqrt.c",
-        "upstream-freebsd/lib/msun/src/e_sqrtf.c",
         "upstream-freebsd/lib/msun/src/k_cos.c",
         "upstream-freebsd/lib/msun/src/k_cosf.c",
         "upstream-freebsd/lib/msun/src/k_exp.c",
@@ -282,24 +280,16 @@
         },
     },
 
-    // arch-specific settings
     arch: {
         arm: {
             srcs: [
                 "arm/fenv.c",
+                "arm/floor.S",
+                "arm/sqrt.S",
             ],
-            neon: {
-                srcs: [
-                    "arm/sqrt.S",
-                    "arm/floor.S",
-                ],
-
-                exclude_srcs: [
-                    "upstream-freebsd/lib/msun/src/e_sqrt.c",
-                    "upstream-freebsd/lib/msun/src/e_sqrtf.c",
-                    "upstream-freebsd/lib/msun/src/s_floor.c",
-                ],
-            },
+            exclude_srcs: [
+                "upstream-freebsd/lib/msun/src/s_floor.c",
+            ],
             instruction_set: "arm",
             pack_relocations: false,
             ldflags: ["-Wl,--hash-style=both"],
@@ -318,10 +308,10 @@
                 "arm64/sqrt.S",
             ],
             exclude_srcs: [
-                "upstream-freebsd/lib/msun/src/e_sqrt.c",
-                "upstream-freebsd/lib/msun/src/e_sqrtf.c",
                 "upstream-freebsd/lib/msun/src/s_ceil.c",
                 "upstream-freebsd/lib/msun/src/s_ceilf.c",
+                "upstream-freebsd/lib/msun/src/s_copysign.c",
+                "upstream-freebsd/lib/msun/src/s_copysignf.c",
                 "upstream-freebsd/lib/msun/src/s_floor.c",
                 "upstream-freebsd/lib/msun/src/s_floorf.c",
                 "upstream-freebsd/lib/msun/src/s_fma.c",
@@ -332,8 +322,12 @@
                 "upstream-freebsd/lib/msun/src/s_fminf.c",
                 "upstream-freebsd/lib/msun/src/s_llrint.c",
                 "upstream-freebsd/lib/msun/src/s_llrintf.c",
+                "upstream-freebsd/lib/msun/src/s_llround.c",
+                "upstream-freebsd/lib/msun/src/s_llroundf.c",
                 "upstream-freebsd/lib/msun/src/s_lrint.c",
                 "upstream-freebsd/lib/msun/src/s_lrintf.c",
+                "upstream-freebsd/lib/msun/src/s_lround.c",
+                "upstream-freebsd/lib/msun/src/s_lroundf.c",
                 "upstream-freebsd/lib/msun/src/s_rint.c",
                 "upstream-freebsd/lib/msun/src/s_rintf.c",
                 "upstream-freebsd/lib/msun/src/s_round.c",
@@ -344,6 +338,22 @@
             version_script: ":libm.arm64.map",
         },
 
+        riscv64: {
+            srcs: [
+                "riscv64/fenv.c",
+                "riscv64/lrint.S",
+                "riscv64/sqrt.S",
+            ],
+
+            exclude_srcs: [
+                "upstream-freebsd/lib/msun/src/s_llrint.c",
+                "upstream-freebsd/lib/msun/src/s_llrintf.c",
+                "upstream-freebsd/lib/msun/src/s_lrint.c",
+                "upstream-freebsd/lib/msun/src/s_lrintf.c",
+            ],
+            version_script: ":libm.riscv64.map",
+        },
+
         x86: {
             srcs: [
                 "i387/fenv.c",
@@ -386,8 +396,6 @@
                 "upstream-freebsd/lib/msun/src/e_hypot.c",
                 "upstream-freebsd/lib/msun/src/e_log10.c",
                 "upstream-freebsd/lib/msun/src/e_sinh.c",
-                "upstream-freebsd/lib/msun/src/e_sqrt.c",
-                "upstream-freebsd/lib/msun/src/e_sqrtf.c",
                 "upstream-freebsd/lib/msun/src/s_atan.c",
                 "upstream-freebsd/lib/msun/src/s_cbrt.c",
                 "upstream-freebsd/lib/msun/src/s_ceil.c",
@@ -452,8 +460,6 @@
                 "upstream-freebsd/lib/msun/src/e_hypot.c",
                 "upstream-freebsd/lib/msun/src/e_log10.c",
                 "upstream-freebsd/lib/msun/src/e_sinh.c",
-                "upstream-freebsd/lib/msun/src/e_sqrt.c",
-                "upstream-freebsd/lib/msun/src/e_sqrtf.c",
                 "upstream-freebsd/lib/msun/src/s_atan.c",
                 "upstream-freebsd/lib/msun/src/s_cbrt.c",
                 "upstream-freebsd/lib/msun/src/s_ceil.c",
@@ -573,6 +579,14 @@
 }
 
 genrule {
+    name: "libm.riscv64.map",
+    out: ["libm.riscv64.map"],
+    srcs: ["libm.map.txt"],
+    tools: ["generate-version-script"],
+    cmd: "$(location generate-version-script) riscv64 $(in) $(out)",
+}
+
+genrule {
     name: "libm.x86.map",
     out: ["libm.x86.map"],
     srcs: ["libm.map.txt"],
diff --git a/libm/NOTICE b/libm/NOTICE
index 64d253a..bce49ad 100644
--- a/libm/NOTICE
+++ b/libm/NOTICE
@@ -309,6 +309,34 @@
 
 -------------------------------------------------------------------
 
+Copyright (C) 2022 The Android Open Source Project
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+ * Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in
+   the documentation and/or other materials provided with the
+   distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+
+-------------------------------------------------------------------
+
 Copyright (c) 1985, 1993
    The Regents of the University of California.  All rights reserved.
 
diff --git a/libm/arm64/fenv.c b/libm/arm64/fenv.c
index a99288b..0f28d0c 100644
--- a/libm/arm64/fenv.c
+++ b/libm/arm64/fenv.c
@@ -59,7 +59,6 @@
 
 int fesetenv(const fenv_t* envp) {
   fpu_control_t fpcr;
-
   __get_fpcr(fpcr);
   if (envp->__control != fpcr) {
     __set_fpcr(envp->__control);
@@ -70,27 +69,22 @@
 
 int feclearexcept(int excepts) {
   fpu_status_t fpsr;
-
-  excepts &= FE_ALL_EXCEPT;
   __get_fpsr(fpsr);
-  fpsr &= ~excepts;
+  fpsr &= ~(excepts & FE_ALL_EXCEPT);
   __set_fpsr(fpsr);
   return 0;
 }
 
 int fegetexceptflag(fexcept_t* flagp, int excepts) {
   fpu_status_t fpsr;
-
-  excepts &= FE_ALL_EXCEPT;
   __get_fpsr(fpsr);
-  *flagp = fpsr & excepts;
+  *flagp = fpsr & (excepts & FE_ALL_EXCEPT);
   return 0;
 }
 
 int fesetexceptflag(const fexcept_t* flagp, int excepts) {
-  fpu_status_t fpsr;
-
   excepts &= FE_ALL_EXCEPT;
+  fpu_status_t fpsr;
   __get_fpsr(fpsr);
   fpsr &= ~excepts;
   fpsr |= *flagp & excepts;
@@ -100,32 +94,27 @@
 
 int feraiseexcept(int excepts) {
   fexcept_t ex = excepts;
-
   fesetexceptflag(&ex, excepts);
   return 0;
 }
 
 int fetestexcept(int excepts) {
   fpu_status_t fpsr;
-
-  excepts &= FE_ALL_EXCEPT;
   __get_fpsr(fpsr);
-  return (fpsr & excepts);
+  return (fpsr & (excepts & FE_ALL_EXCEPT));
 }
 
 int fegetround(void) {
   fpu_control_t fpcr;
-
   __get_fpcr(fpcr);
   return ((fpcr >> FPCR_RMODE_SHIFT) & FE_TOWARDZERO);
 }
 
 int fesetround(int round) {
-  fpu_control_t fpcr, new_fpcr;
-
-  round &= FE_TOWARDZERO;
+  if (round < FE_TONEAREST || round > FE_TOWARDZERO) return -1;
+  fpu_control_t fpcr;
   __get_fpcr(fpcr);
-  new_fpcr = fpcr & ~(FE_TOWARDZERO << FPCR_RMODE_SHIFT);
+  fpu_control_t new_fpcr = fpcr & ~(FE_TOWARDZERO << FPCR_RMODE_SHIFT);
   new_fpcr |= (round << FPCR_RMODE_SHIFT);
   if (new_fpcr != fpcr) {
     __set_fpcr(new_fpcr);
@@ -134,33 +123,15 @@
 }
 
 int feholdexcept(fenv_t* envp) {
-  fpu_status_t fpsr;
-  __get_fpsr(fpsr);
-  fpu_control_t fpcr;
-  __get_fpcr(fpcr);
-  fenv_t env = { .__status = fpsr, .__control = fpcr };
-  *envp = env;
-
-  // Clear all exceptions.
-  fpsr &= ~FE_ALL_EXCEPT;
-  __set_fpsr(fpsr);
+  fegetenv(envp);
+  feclearexcept(FE_ALL_EXCEPT);
   return 0;
 }
 
 int feupdateenv(const fenv_t* envp) {
-  fpu_status_t fpsr;
-  fpu_control_t fpcr;
-
-  // Set FPU Control register.
-  __get_fpcr(fpcr);
-  if (envp->__control != fpcr) {
-    __set_fpcr(envp->__control);
-  }
-
-  // Set FPU Status register to status | currently raised exceptions.
-  __get_fpsr(fpsr);
-  fpsr = envp->__status | (fpsr & FE_ALL_EXCEPT);
-  __set_fpsr(fpsr);
+  int excepts = fetestexcept(FE_ALL_EXCEPT);
+  fesetenv(envp);
+  feraiseexcept(excepts);
   return 0;
 }
 
diff --git a/libm/builtins.cpp b/libm/builtins.cpp
index 3b9228c..7487323 100644
--- a/libm/builtins.cpp
+++ b/libm/builtins.cpp
@@ -49,6 +49,9 @@
 float ceilf(float x) { return __builtin_ceilf(x); }
 double ceil(double x) { return __builtin_ceil(x); }
 
+double copysign(double x, double y) { return __builtin_copysign(x, y); }
+float copysignf(float x, float y) { return __builtin_copysignf(x, y); }
+
 float floorf(float x) { return __builtin_floorf(x); }
 double floor(double x) { return __builtin_floor(x); }
 
@@ -61,6 +64,11 @@
 float fminf(float x, float y) { return __builtin_fminf(x, y); }
 double fmin(double x, double y) { return __builtin_fmin(x, y); }
 
+long lround(double x) { return __builtin_lround(x); }
+long lroundf(float x) { return __builtin_lroundf(x); }
+long long llround(double x) { return __builtin_llround(x); }
+long long llroundf(float x) { return __builtin_llroundf(x); }
+
 float rintf(float x) { return __builtin_rintf(x); }
 double rint(double x) { return __builtin_rint(x); }
 
diff --git a/libm/riscv64/fenv.c b/libm/riscv64/fenv.c
new file mode 100644
index 0000000..f16e5a9
--- /dev/null
+++ b/libm/riscv64/fenv.c
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <fenv.h>
+#include <stdint.h>
+
+const fenv_t __fe_dfl_env = 0;
+
+int fegetenv(fenv_t* envp) {
+  __asm__ __volatile__("frcsr %0" : "=r"(*envp));
+  return 0;
+}
+
+int fesetenv(const fenv_t* envp) {
+  fenv_t env;
+  fegetenv(&env);
+  if (*envp != env) {
+    __asm__ __volatile__("fscsr %z0" : : "r"(*envp));
+  }
+  return 0;
+}
+
+int feclearexcept(int excepts) {
+  __asm__ __volatile__("csrc fflags, %0" : : "r"(excepts & FE_ALL_EXCEPT));
+  return 0;
+}
+
+int fegetexceptflag(fexcept_t* flagp, int excepts) {
+  *flagp = fetestexcept(excepts & FE_ALL_EXCEPT);
+  return 0;
+}
+
+int fesetexceptflag(const fexcept_t* flagp, int excepts) {
+  feclearexcept((~*flagp) & excepts);
+  feraiseexcept(*flagp & excepts);
+  return 0;
+}
+
+int feraiseexcept(int excepts) {
+  __asm__ __volatile__("csrs fflags, %0" : : "r"(excepts));
+  return 0;
+}
+
+int fetestexcept(int excepts) {
+  int flags;
+  __asm__ __volatile__("frflags %0" : "=r"(flags));
+  return flags & excepts;
+}
+
+int fegetround(void) {
+  int rm;
+  __asm__ __volatile__("frrm %0" : "=r"(rm));
+  return rm;
+}
+
+int fesetround(int round) {
+  if (round < FE_TONEAREST || round > FE_UPWARD) return -1;
+  __asm__ __volatile__("fsrm %z0" : : "r"(round));
+  return 0;
+}
+
+int feholdexcept(fenv_t* envp) {
+  fegetenv(envp);
+  feclearexcept(FE_ALL_EXCEPT);
+  return 0;
+}
+
+int feupdateenv(const fenv_t* envp) {
+  int excepts = fetestexcept(FE_ALL_EXCEPT);
+  fesetenv(envp);
+  feraiseexcept(excepts);
+  return 0;
+}
+
+int feenableexcept(int mask __unused) {
+  return -1;
+}
+
+int fedisableexcept(int mask __unused) {
+  return 0;
+}
+
+int fegetexcept(void) {
+  return 0;
+}
diff --git a/libm/riscv64/lrint.S b/libm/riscv64/lrint.S
new file mode 100644
index 0000000..eb13833
--- /dev/null
+++ b/libm/riscv64/lrint.S
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <private/bionic_asm.h>
+
+ENTRY(lrint)
+  fcvt.l.d a0, fa0, dyn
+  ret
+END(lrint)
+
+ENTRY(lrintf)
+  fcvt.l.s a0, fa0, dyn
+  ret
+END(lrintf)
+
+// sizeof(long) and sizeof(long long) are the same for riscv64
+ALIAS_SYMBOL(llrint, lrint);
+
+ALIAS_SYMBOL(llrintf, lrintf);
diff --git a/libm/riscv64/sqrt.S b/libm/riscv64/sqrt.S
new file mode 100644
index 0000000..0db1335
--- /dev/null
+++ b/libm/riscv64/sqrt.S
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <private/bionic_asm.h>
+
+ENTRY(sqrt)
+  fsqrt.d fa0, fa0
+  ret
+END(sqrt)
+
+ENTRY(sqrtf)
+  fsqrt.s fa0, fa0
+  ret
+END(sqrtf)
diff --git a/libm/upstream-freebsd/lib/msun/src/e_sqrt.c b/libm/upstream-freebsd/lib/msun/src/e_sqrt.c
deleted file mode 100644
index 37351a4..0000000
--- a/libm/upstream-freebsd/lib/msun/src/e_sqrt.c
+++ /dev/null
@@ -1,459 +0,0 @@
-
-/* @(#)e_sqrt.c 1.3 95/01/18 */
-/*
- * ====================================================
- * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
- *
- * Developed at SunSoft, a Sun Microsystems, Inc. business.
- * Permission to use, copy, modify, and distribute this
- * software is freely granted, provided that this notice 
- * is preserved.
- * ====================================================
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <float.h>
-
-#include "math.h"
-#include "math_private.h"
-
-#ifdef USE_BUILTIN_SQRT
-double
-__ieee754_sqrt(double x)
-{
-	return (__builtin_sqrt(x));
-}
-#else
-/* __ieee754_sqrt(x)
- * Return correctly rounded sqrt.
- *           ------------------------------------------
- *	     |  Use the hardware sqrt if you have one |
- *           ------------------------------------------
- * Method: 
- *   Bit by bit method using integer arithmetic. (Slow, but portable) 
- *   1. Normalization
- *	Scale x to y in [1,4) with even powers of 2: 
- *	find an integer k such that  1 <= (y=x*2^(2k)) < 4, then
- *		sqrt(x) = 2^k * sqrt(y)
- *   2. Bit by bit computation
- *	Let q  = sqrt(y) truncated to i bit after binary point (q = 1),
- *	     i							 0
- *                                     i+1         2
- *	    s  = 2*q , and	y  =  2   * ( y - q  ).		(1)
- *	     i      i            i                 i
- *                                                        
- *	To compute q    from q , one checks whether 
- *		    i+1       i                       
- *
- *			      -(i+1) 2
- *			(q + 2      ) <= y.			(2)
- *     			  i
- *							      -(i+1)
- *	If (2) is false, then q   = q ; otherwise q   = q  + 2      .
- *		 	       i+1   i             i+1   i
- *
- *	With some algebric manipulation, it is not difficult to see
- *	that (2) is equivalent to 
- *                             -(i+1)
- *			s  +  2       <= y			(3)
- *			 i                i
- *
- *	The advantage of (3) is that s  and y  can be computed by 
- *				      i      i
- *	the following recurrence formula:
- *	    if (3) is false
- *
- *	    s     =  s  ,	y    = y   ;			(4)
- *	     i+1      i		 i+1    i
- *
- *	    otherwise,
- *                         -i                     -(i+1)
- *	    s	  =  s  + 2  ,  y    = y  -  s  - 2  		(5)
- *           i+1      i          i+1    i     i
- *				
- *	One may easily use induction to prove (4) and (5). 
- *	Note. Since the left hand side of (3) contain only i+2 bits,
- *	      it does not necessary to do a full (53-bit) comparison 
- *	      in (3).
- *   3. Final rounding
- *	After generating the 53 bits result, we compute one more bit.
- *	Together with the remainder, we can decide whether the
- *	result is exact, bigger than 1/2ulp, or less than 1/2ulp
- *	(it will never equal to 1/2ulp).
- *	The rounding mode can be detected by checking whether
- *	huge + tiny is equal to huge, and whether huge - tiny is
- *	equal to huge for some floating point number "huge" and "tiny".
- *		
- * Special cases:
- *	sqrt(+-0) = +-0 	... exact
- *	sqrt(inf) = inf
- *	sqrt(-ve) = NaN		... with invalid signal
- *	sqrt(NaN) = NaN		... with invalid signal for signaling NaN
- *
- * Other methods : see the appended file at the end of the program below.
- *---------------
- */
-
-static	const double	one	= 1.0, tiny=1.0e-300;
-
-double
-__ieee754_sqrt(double x)
-{
-	double z;
-	int32_t sign = (int)0x80000000;
-	int32_t ix0,s0,q,m,t,i;
-	u_int32_t r,t1,s1,ix1,q1;
-
-	EXTRACT_WORDS(ix0,ix1,x);
-
-    /* take care of Inf and NaN */
-	if((ix0&0x7ff00000)==0x7ff00000) {			
-	    return x*x+x;		/* sqrt(NaN)=NaN, sqrt(+inf)=+inf
-					   sqrt(-inf)=sNaN */
-	} 
-    /* take care of zero */
-	if(ix0<=0) {
-	    if(((ix0&(~sign))|ix1)==0) return x;/* sqrt(+-0) = +-0 */
-	    else if(ix0<0)
-		return (x-x)/(x-x);		/* sqrt(-ve) = sNaN */
-	}
-    /* normalize x */
-	m = (ix0>>20);
-	if(m==0) {				/* subnormal x */
-	    while(ix0==0) {
-		m -= 21;
-		ix0 |= (ix1>>11); ix1 <<= 21;
-	    }
-	    for(i=0;(ix0&0x00100000)==0;i++) ix0<<=1;
-	    m -= i-1;
-	    ix0 |= (ix1>>(32-i));
-	    ix1 <<= i;
-	}
-	m -= 1023;	/* unbias exponent */
-	ix0 = (ix0&0x000fffff)|0x00100000;
-	if(m&1){	/* odd m, double x to make it even */
-	    ix0 += ix0 + ((ix1&sign)>>31);
-	    ix1 += ix1;
-	}
-	m >>= 1;	/* m = [m/2] */
-
-    /* generate sqrt(x) bit by bit */
-	ix0 += ix0 + ((ix1&sign)>>31);
-	ix1 += ix1;
-	q = q1 = s0 = s1 = 0;	/* [q,q1] = sqrt(x) */
-	r = 0x00200000;		/* r = moving bit from right to left */
-
-	while(r!=0) {
-	    t = s0+r; 
-	    if(t<=ix0) { 
-		s0   = t+r; 
-		ix0 -= t; 
-		q   += r; 
-	    } 
-	    ix0 += ix0 + ((ix1&sign)>>31);
-	    ix1 += ix1;
-	    r>>=1;
-	}
-
-	r = sign;
-	while(r!=0) {
-	    t1 = s1+r; 
-	    t  = s0;
-	    if((t<ix0)||((t==ix0)&&(t1<=ix1))) { 
-		s1  = t1+r;
-		if(((t1&sign)==sign)&&(s1&sign)==0) s0 += 1;
-		ix0 -= t;
-		if (ix1 < t1) ix0 -= 1;
-		ix1 -= t1;
-		q1  += r;
-	    }
-	    ix0 += ix0 + ((ix1&sign)>>31);
-	    ix1 += ix1;
-	    r>>=1;
-	}
-
-    /* use floating add to find out rounding direction */
-	if((ix0|ix1)!=0) {
-	    z = one-tiny; /* trigger inexact flag */
-	    if (z>=one) {
-	        z = one+tiny;
-	        if (q1==(u_int32_t)0xffffffff) { q1=0; q += 1;}
-		else if (z>one) {
-		    if (q1==(u_int32_t)0xfffffffe) q+=1;
-		    q1+=2; 
-		} else
-	            q1 += (q1&1);
-	    }
-	}
-	ix0 = (q>>1)+0x3fe00000;
-	ix1 =  q1>>1;
-	if ((q&1)==1) ix1 |= sign;
-	ix0 += (m <<20);
-	INSERT_WORDS(z,ix0,ix1);
-	return z;
-}
-#endif
-
-#if (LDBL_MANT_DIG == 53)
-__weak_reference(sqrt, sqrtl);
-#endif
-
-/*
-Other methods  (use floating-point arithmetic)
--------------
-(This is a copy of a drafted paper by Prof W. Kahan 
-and K.C. Ng, written in May, 1986)
-
-	Two algorithms are given here to implement sqrt(x) 
-	(IEEE double precision arithmetic) in software.
-	Both supply sqrt(x) correctly rounded. The first algorithm (in
-	Section A) uses newton iterations and involves four divisions.
-	The second one uses reciproot iterations to avoid division, but
-	requires more multiplications. Both algorithms need the ability
-	to chop results of arithmetic operations instead of round them, 
-	and the INEXACT flag to indicate when an arithmetic operation
-	is executed exactly with no roundoff error, all part of the 
-	standard (IEEE 754-1985). The ability to perform shift, add,
-	subtract and logical AND operations upon 32-bit words is needed
-	too, though not part of the standard.
-
-A.  sqrt(x) by Newton Iteration
-
-   (1)	Initial approximation
-
-	Let x0 and x1 be the leading and the trailing 32-bit words of
-	a floating point number x (in IEEE double format) respectively 
-
-	    1    11		     52				  ...widths
-	   ------------------------------------------------------
-	x: |s|	  e     |	      f				|
-	   ------------------------------------------------------
-	      msb    lsb  msb				      lsb ...order
-
- 
-	     ------------------------  	     ------------------------
-	x0:  |s|   e    |    f1     |	 x1: |          f2           |
-	     ------------------------  	     ------------------------
-
-	By performing shifts and subtracts on x0 and x1 (both regarded
-	as integers), we obtain an 8-bit approximation of sqrt(x) as
-	follows.
-
-		k  := (x0>>1) + 0x1ff80000;
-		y0 := k - T1[31&(k>>15)].	... y ~ sqrt(x) to 8 bits
-	Here k is a 32-bit integer and T1[] is an integer array containing
-	correction terms. Now magically the floating value of y (y's
-	leading 32-bit word is y0, the value of its trailing word is 0)
-	approximates sqrt(x) to almost 8-bit.
-
-	Value of T1:
-	static int T1[32]= {
-	0,	1024,	3062,	5746,	9193,	13348,	18162,	23592,
-	29598,	36145,	43202,	50740,	58733,	67158,	75992,	85215,
-	83599,	71378,	60428,	50647,	41945,	34246,	27478,	21581,
-	16499,	12183,	8588,	5674,	3403,	1742,	661,	130,};
-
-    (2)	Iterative refinement
-
-	Apply Heron's rule three times to y, we have y approximates 
-	sqrt(x) to within 1 ulp (Unit in the Last Place):
-
-		y := (y+x/y)/2		... almost 17 sig. bits
-		y := (y+x/y)/2		... almost 35 sig. bits
-		y := y-(y-x/y)/2	... within 1 ulp
-
-
-	Remark 1.
-	    Another way to improve y to within 1 ulp is:
-
-		y := (y+x/y)		... almost 17 sig. bits to 2*sqrt(x)
-		y := y - 0x00100006	... almost 18 sig. bits to sqrt(x)
-
-				2
-			    (x-y )*y
-		y := y + 2* ----------	...within 1 ulp
-			       2
-			     3y  + x
-
-
-	This formula has one division fewer than the one above; however,
-	it requires more multiplications and additions. Also x must be
-	scaled in advance to avoid spurious overflow in evaluating the
-	expression 3y*y+x. Hence it is not recommended uless division
-	is slow. If division is very slow, then one should use the 
-	reciproot algorithm given in section B.
-
-    (3) Final adjustment
-
-	By twiddling y's last bit it is possible to force y to be 
-	correctly rounded according to the prevailing rounding mode
-	as follows. Let r and i be copies of the rounding mode and
-	inexact flag before entering the square root program. Also we
-	use the expression y+-ulp for the next representable floating
-	numbers (up and down) of y. Note that y+-ulp = either fixed
-	point y+-1, or multiply y by nextafter(1,+-inf) in chopped
-	mode.
-
-		I := FALSE;	... reset INEXACT flag I
-		R := RZ;	... set rounding mode to round-toward-zero
-		z := x/y;	... chopped quotient, possibly inexact
-		If(not I) then {	... if the quotient is exact
-		    if(z=y) {
-		        I := i;	 ... restore inexact flag
-		        R := r;  ... restore rounded mode
-		        return sqrt(x):=y.
-		    } else {
-			z := z - ulp;	... special rounding
-		    }
-		}
-		i := TRUE;		... sqrt(x) is inexact
-		If (r=RN) then z=z+ulp	... rounded-to-nearest
-		If (r=RP) then {	... round-toward-+inf
-		    y = y+ulp; z=z+ulp;
-		}
-		y := y+z;		... chopped sum
-		y0:=y0-0x00100000;	... y := y/2 is correctly rounded.
-	        I := i;	 		... restore inexact flag
-	        R := r;  		... restore rounded mode
-	        return sqrt(x):=y.
-		    
-    (4)	Special cases
-
-	Square root of +inf, +-0, or NaN is itself;
-	Square root of a negative number is NaN with invalid signal.
-
-
-B.  sqrt(x) by Reciproot Iteration
-
-   (1)	Initial approximation
-
-	Let x0 and x1 be the leading and the trailing 32-bit words of
-	a floating point number x (in IEEE double format) respectively
-	(see section A). By performing shifs and subtracts on x0 and y0,
-	we obtain a 7.8-bit approximation of 1/sqrt(x) as follows.
-
-	    k := 0x5fe80000 - (x0>>1);
-	    y0:= k - T2[63&(k>>14)].	... y ~ 1/sqrt(x) to 7.8 bits
-
-	Here k is a 32-bit integer and T2[] is an integer array 
-	containing correction terms. Now magically the floating
-	value of y (y's leading 32-bit word is y0, the value of
-	its trailing word y1 is set to zero) approximates 1/sqrt(x)
-	to almost 7.8-bit.
-
-	Value of T2:
-	static int T2[64]= {
-	0x1500,	0x2ef8,	0x4d67,	0x6b02,	0x87be,	0xa395,	0xbe7a,	0xd866,
-	0xf14a,	0x1091b,0x11fcd,0x13552,0x14999,0x15c98,0x16e34,0x17e5f,
-	0x18d03,0x19a01,0x1a545,0x1ae8a,0x1b5c4,0x1bb01,0x1bfde,0x1c28d,
-	0x1c2de,0x1c0db,0x1ba73,0x1b11c,0x1a4b5,0x1953d,0x18266,0x16be0,
-	0x1683e,0x179d8,0x18a4d,0x19992,0x1a789,0x1b445,0x1bf61,0x1c989,
-	0x1d16d,0x1d77b,0x1dddf,0x1e2ad,0x1e5bf,0x1e6e8,0x1e654,0x1e3cd,
-	0x1df2a,0x1d635,0x1cb16,0x1be2c,0x1ae4e,0x19bde,0x1868e,0x16e2e,
-	0x1527f,0x1334a,0x11051,0xe951,	0xbe01,	0x8e0d,	0x5924,	0x1edd,};
-
-    (2)	Iterative refinement
-
-	Apply Reciproot iteration three times to y and multiply the
-	result by x to get an approximation z that matches sqrt(x)
-	to about 1 ulp. To be exact, we will have 
-		-1ulp < sqrt(x)-z<1.0625ulp.
-	
-	... set rounding mode to Round-to-nearest
-	   y := y*(1.5-0.5*x*y*y)	... almost 15 sig. bits to 1/sqrt(x)
-	   y := y*((1.5-2^-30)+0.5*x*y*y)... about 29 sig. bits to 1/sqrt(x)
-	... special arrangement for better accuracy
-	   z := x*y			... 29 bits to sqrt(x), with z*y<1
-	   z := z + 0.5*z*(1-z*y)	... about 1 ulp to sqrt(x)
-
-	Remark 2. The constant 1.5-2^-30 is chosen to bias the error so that
-	(a) the term z*y in the final iteration is always less than 1; 
-	(b) the error in the final result is biased upward so that
-		-1 ulp < sqrt(x) - z < 1.0625 ulp
-	    instead of |sqrt(x)-z|<1.03125ulp.
-
-    (3)	Final adjustment
-
-	By twiddling y's last bit it is possible to force y to be 
-	correctly rounded according to the prevailing rounding mode
-	as follows. Let r and i be copies of the rounding mode and
-	inexact flag before entering the square root program. Also we
-	use the expression y+-ulp for the next representable floating
-	numbers (up and down) of y. Note that y+-ulp = either fixed
-	point y+-1, or multiply y by nextafter(1,+-inf) in chopped
-	mode.
-
-	R := RZ;		... set rounding mode to round-toward-zero
-	switch(r) {
-	    case RN:		... round-to-nearest
-	       if(x<= z*(z-ulp)...chopped) z = z - ulp; else
-	       if(x<= z*(z+ulp)...chopped) z = z; else z = z+ulp;
-	       break;
-	    case RZ:case RM:	... round-to-zero or round-to--inf
-	       R:=RP;		... reset rounding mod to round-to-+inf
-	       if(x<z*z ... rounded up) z = z - ulp; else
-	       if(x>=(z+ulp)*(z+ulp) ...rounded up) z = z+ulp;
-	       break;
-	    case RP:		... round-to-+inf
-	       if(x>(z+ulp)*(z+ulp)...chopped) z = z+2*ulp; else
-	       if(x>z*z ...chopped) z = z+ulp;
-	       break;
-	}
-
-	Remark 3. The above comparisons can be done in fixed point. For
-	example, to compare x and w=z*z chopped, it suffices to compare
-	x1 and w1 (the trailing parts of x and w), regarding them as
-	two's complement integers.
-
-	...Is z an exact square root?
-	To determine whether z is an exact square root of x, let z1 be the
-	trailing part of z, and also let x0 and x1 be the leading and
-	trailing parts of x.
-
-	If ((z1&0x03ffffff)!=0)	... not exact if trailing 26 bits of z!=0
-	    I := 1;		... Raise Inexact flag: z is not exact
-	else {
-	    j := 1 - [(x0>>20)&1]	... j = logb(x) mod 2
-	    k := z1 >> 26;		... get z's 25-th and 26-th 
-					    fraction bits
-	    I := i or (k&j) or ((k&(j+j+1))!=(x1&3));
-	}
-	R:= r		... restore rounded mode
-	return sqrt(x):=z.
-
-	If multiplication is cheaper then the foregoing red tape, the 
-	Inexact flag can be evaluated by
-
-	    I := i;
-	    I := (z*z!=x) or I.
-
-	Note that z*z can overwrite I; this value must be sensed if it is 
-	True.
-
-	Remark 4. If z*z = x exactly, then bit 25 to bit 0 of z1 must be
-	zero.
-
-		    --------------------
-		z1: |        f2        | 
-		    --------------------
-		bit 31		   bit 0
-
-	Further more, bit 27 and 26 of z1, bit 0 and 1 of x1, and the odd
-	or even of logb(x) have the following relations:
-
-	-------------------------------------------------
-	bit 27,26 of z1		bit 1,0 of x1	logb(x)
-	-------------------------------------------------
-	00			00		odd and even
-	01			01		even
-	10			10		odd
-	10			00		even
-	11			01		even
-	-------------------------------------------------
-
-    (4)	Special cases (see (4) of Section A).	
- 
- */
- 
diff --git a/libm/upstream-freebsd/lib/msun/src/e_sqrtf.c b/libm/upstream-freebsd/lib/msun/src/e_sqrtf.c
deleted file mode 100644
index 06e5d62..0000000
--- a/libm/upstream-freebsd/lib/msun/src/e_sqrtf.c
+++ /dev/null
@@ -1,97 +0,0 @@
-/* e_sqrtf.c -- float version of e_sqrt.c.
- * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
- */
-
-/*
- * ====================================================
- * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
- *
- * Developed at SunPro, a Sun Microsystems, Inc. business.
- * Permission to use, copy, modify, and distribute this
- * software is freely granted, provided that this notice
- * is preserved.
- * ====================================================
- */
-
-#ifndef lint
-static char rcsid[] = "$FreeBSD$";
-#endif
-
-#include "math.h"
-#include "math_private.h"
-
-#ifdef USE_BUILTIN_SQRTF
-float
-__ieee754_sqrtf(float x)
-{
-	return (__builtin_sqrtf(x));
-}
-#else
-static	const float	one	= 1.0, tiny=1.0e-30;
-
-float
-__ieee754_sqrtf(float x)
-{
-	float z;
-	int32_t sign = (int)0x80000000;
-	int32_t ix,s,q,m,t,i;
-	u_int32_t r;
-
-	GET_FLOAT_WORD(ix,x);
-
-    /* take care of Inf and NaN */
-	if((ix&0x7f800000)==0x7f800000) {
-	    return x*x+x;		/* sqrt(NaN)=NaN, sqrt(+inf)=+inf
-					   sqrt(-inf)=sNaN */
-	}
-    /* take care of zero */
-	if(ix<=0) {
-	    if((ix&(~sign))==0) return x;/* sqrt(+-0) = +-0 */
-	    else if(ix<0)
-		return (x-x)/(x-x);		/* sqrt(-ve) = sNaN */
-	}
-    /* normalize x */
-	m = (ix>>23);
-	if(m==0) {				/* subnormal x */
-	    for(i=0;(ix&0x00800000)==0;i++) ix<<=1;
-	    m -= i-1;
-	}
-	m -= 127;	/* unbias exponent */
-	ix = (ix&0x007fffff)|0x00800000;
-	if(m&1)	/* odd m, double x to make it even */
-	    ix += ix;
-	m >>= 1;	/* m = [m/2] */
-
-    /* generate sqrt(x) bit by bit */
-	ix += ix;
-	q = s = 0;		/* q = sqrt(x) */
-	r = 0x01000000;		/* r = moving bit from right to left */
-
-	while(r!=0) {
-	    t = s+r;
-	    if(t<=ix) {
-		s    = t+r;
-		ix  -= t;
-		q   += r;
-	    }
-	    ix += ix;
-	    r>>=1;
-	}
-
-    /* use floating add to find out rounding direction */
-	if(ix!=0) {
-	    z = one-tiny; /* trigger inexact flag */
-	    if (z>=one) {
-	        z = one+tiny;
-		if (z>one)
-		    q += 2;
-		else
-		    q += (q&1);
-	    }
-	}
-	ix = (q>>1)+0x3f000000;
-	ix += (m <<23);
-	SET_FLOAT_WORD(z,ix);
-	return z;
-}
-#endif
diff --git a/linker/Android.bp b/linker/Android.bp
index 57420a9..83077c6 100644
--- a/linker/Android.bp
+++ b/linker/Android.bp
@@ -52,6 +52,9 @@
         arm64: {
             srcs: ["arch/arm64/linker_wrapper_begin.S"],
         },
+        riscv64: {
+            srcs: ["arch/riscv64/linker_wrapper_begin.S"],
+        },
         x86_64: {
             srcs: ["arch/x86_64/linker_wrapper_begin.S"],
         },
@@ -208,6 +211,13 @@
 }
 
 filegroup {
+    name: "linker_sources_riscv64",
+    srcs: [
+        "arch/riscv64/begin.S",
+    ],
+}
+
+filegroup {
     name: "linker_sources_x86",
     srcs: [
         "arch/x86/begin.S",
@@ -224,10 +234,11 @@
 cc_defaults {
     name: "linker_version_script_overlay",
     arch: {
-        arm:    { version_script: "linker.arm.map"      },
-        arm64:  { version_script: "linker.generic.map"  },
-        x86:    { version_script: "linker.generic.map"  },
-        x86_64: { version_script: "linker.generic.map"  },
+        arm:     { version_script: "linker.arm.map"      },
+        arm64:   { version_script: "linker.generic.map"  },
+        riscv64: { version_script: "linker.generic.map"  },
+        x86:     { version_script: "linker.generic.map"  },
+        x86_64:  { version_script: "linker.generic.map"  },
     },
 }
 
@@ -259,6 +270,15 @@
                 keep_symbols: true,
             },
         },
+        riscv64: {
+            srcs: [":linker_sources_riscv64"],
+
+            // Leave the symbols in the shared library so that stack unwinders can produce
+            // meaningful name resolution.
+            strip: {
+                keep_symbols: true,
+            },
+        },
         x86: {
             srcs: [":linker_sources_x86"],
 
@@ -426,6 +446,7 @@
         "-Wl,--exclude-libs=libgcc_stripped.a",
         "-Wl,--exclude-libs=libclang_rt.builtins-arm-android.a",
         "-Wl,--exclude-libs=libclang_rt.builtins-aarch64-android.a",
+        "-Wl,--exclude-libs=libclang_rt.builtins-riscv64-android.a",
         "-Wl,--exclude-libs=libclang_rt.builtins-i686-android.a",
         "-Wl,--exclude-libs=libclang_rt.builtins-x86_64-android.a",
     ],
diff --git a/linker/NOTICE b/linker/NOTICE
index 8f70d87..d61a193 100644
--- a/linker/NOTICE
+++ b/linker/NOTICE
@@ -334,3 +334,31 @@
 
 -------------------------------------------------------------------
 
+Copyright (C) 2022 The Android Open Source Project
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+ * Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in
+   the documentation and/or other materials provided with the
+   distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+
+-------------------------------------------------------------------
+
diff --git a/linker/arch/arm/begin.S b/linker/arch/arm/begin.S
index 80d9fe1..3b673f0 100644
--- a/linker/arch/arm/begin.S
+++ b/linker/arch/arm/begin.S
@@ -35,6 +35,6 @@
   mov r0, sp
   bl __linker_init
 
-  /* linker init returns the _entry address in the main image */
+  // __linker_init returns the address of the entry point in the main image.
   bx r0
 END(_start)
diff --git a/linker/arch/arm64/begin.S b/linker/arch/arm64/begin.S
index a947475..14999cd 100644
--- a/linker/arch/arm64/begin.S
+++ b/linker/arch/arm64/begin.S
@@ -35,6 +35,6 @@
   mov x0, sp
   bl __linker_init
 
-  /* linker init returns the _entry address in the main image */
+  // __linker_init returns the address of the entry point in the main image.
   br x0
 END(_start)
diff --git a/linker/arch/riscv64/begin.S b/linker/arch/riscv64/begin.S
new file mode 100644
index 0000000..f7509c6
--- /dev/null
+++ b/linker/arch/riscv64/begin.S
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <private/bionic_asm.h>
+
+ENTRY(_start)
+  // Force unwinds to end in this function.
+  .cfi_undefined ra
+
+  mv a0, sp
+  jal __linker_init
+
+  // __linker_init returns the address of the entry point in the main image.
+  jr a0
+END(_start)
diff --git a/linker/arch/x86/begin.S b/linker/arch/x86/begin.S
index 3812646..81e2740 100644
--- a/linker/arch/x86/begin.S
+++ b/linker/arch/x86/begin.S
@@ -38,6 +38,6 @@
   call __linker_init      // %esp is aligned to 16 before the call.
   addl $16, %esp
 
-  /* linker init returns (%eax) the _entry address in the main image */
+  // __linker_init returns the address of the entry point in the main image.
   jmp *%eax
 END(_start)
diff --git a/linker/arch/x86_64/begin.S b/linker/arch/x86_64/begin.S
index 4722301..baba0db 100644
--- a/linker/arch/x86_64/begin.S
+++ b/linker/arch/x86_64/begin.S
@@ -35,6 +35,6 @@
   mov %rsp, %rdi
   call __linker_init
 
-  /* linker init returns (%rax) the _entry address in the main image */
+  // __linker_init returns the address of the entry point in the main image.
   jmp *%rax
 END(_start)
diff --git a/linker/linker.cpp b/linker/linker.cpp
index d533ac3..9779c8d 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -371,7 +371,7 @@
     char* static_tls = reinterpret_cast<char*>(__get_bionic_tcb()) - layout.offset_bionic_tcb();
     return static_tls + tls_mod.static_offset;
   } else if (should_alloc) {
-    const TlsIndex ti { si_tls->module_id, 0 };
+    const TlsIndex ti { si_tls->module_id, static_cast<size_t>(0 - TLS_DTV_OFFSET) };
     return TLS_GET_ADDR(&ti);
   } else {
     TlsDtv* dtv = __get_tcb_dtv(__get_bionic_tcb());
diff --git a/linker/linker_phdr.cpp b/linker/linker_phdr.cpp
index 60fd776..aa1a208 100644
--- a/linker/linker_phdr.cpp
+++ b/linker/linker_phdr.cpp
@@ -51,6 +51,8 @@
   return EM_AARCH64;
 #elif defined(__i386__)
   return EM_386;
+#elif defined(__riscv)
+  return EM_RISCV;
 #elif defined(__x86_64__)
   return EM_X86_64;
 #endif
diff --git a/linker/linker_relocate.cpp b/linker/linker_relocate.cpp
index c7c7bfb..952dade 100644
--- a/linker/linker_relocate.cpp
+++ b/linker/linker_relocate.cpp
@@ -49,7 +49,9 @@
     case R_GENERIC_TLS_DTPMOD:
     case R_GENERIC_TLS_DTPREL:
     case R_GENERIC_TLS_TPREL:
+#if defined(R_GENERIC_TLSDESC)
     case R_GENERIC_TLSDESC:
+#endif
       return true;
     default:
       return false;
@@ -426,7 +428,7 @@
     case R_GENERIC_TLS_DTPREL:
       count_relocation_if<IsGeneral>(kRelocRelative);
       {
-        const ElfW(Addr) result = sym_addr + get_addend_rel();
+        const ElfW(Addr) result = sym_addr + get_addend_rel() - TLS_DTV_OFFSET;
         trace_reloc("RELO TLS_DTPREL %16p <- %16p %s",
                     rel_target, reinterpret_cast<void*>(result), sym_name);
         *static_cast<ElfW(Addr)*>(rel_target) = result;
diff --git a/linker/linker_relocs.h b/linker/linker_relocs.h
index 93d899e..37a7880 100644
--- a/linker/linker_relocs.h
+++ b/linker/linker_relocs.h
@@ -73,6 +73,20 @@
 #define R_GENERIC_TLS_TPREL     R_386_TLS_TPOFF
 #define R_GENERIC_TLSDESC       R_386_TLS_DESC
 
+#elif defined (__riscv)
+
+#define R_GENERIC_JUMP_SLOT     R_RISCV_JUMP_SLOT
+#define R_GENERIC_ABSOLUTE      R_RISCV_64
+#define R_GENERIC_GLOB_DAT      R_RISCV_64
+#define R_GENERIC_RELATIVE      R_RISCV_RELATIVE
+#define R_GENERIC_IRELATIVE     R_RISCV_IRELATIVE
+#define R_GENERIC_COPY          R_RISCV_COPY
+#define R_GENERIC_TLS_DTPMOD    R_RISCV_TLS_DTPMOD64
+#define R_GENERIC_TLS_DTPREL    R_RISCV_TLS_DTPREL64
+#define R_GENERIC_TLS_TPREL     R_RISCV_TLS_TPREL64
+// TODO: https://github.com/riscv-non-isa/riscv-elf-psabi-doc/issues/94
+// #define R_GENERIC_TLSDESC       R_RISCV_TLS_DESC
+
 #elif defined (__x86_64__)
 
 #define R_GENERIC_JUMP_SLOT     R_X86_64_JUMP_SLOT
diff --git a/tests/dl_test.cpp b/tests/dl_test.cpp
index a61586b..2f3e905 100644
--- a/tests/dl_test.cpp
+++ b/tests/dl_test.cpp
@@ -32,9 +32,10 @@
 #include <regex>
 #include <string>
 
-#include "gtest_globals.h"
 #include <android-base/file.h>
+#include <android-base/macros.h>
 #include <android-base/test_utils.h>
+#include "gtest_globals.h"
 #include "utils.h"
 
 extern "C" int main_global_default_serial() {
@@ -84,22 +85,13 @@
 
 #if defined(__BIONIC__)
 #if defined(__LP64__)
-  static constexpr const char* kPathToLinker = "/system/bin/linker64";
+#define LINKER_NAME "linker64"
 #else
-  static constexpr const char* kPathToLinker = "/system/bin/linker";
+#define LINKER_NAME "linker"
 #endif
-
-#if defined (__aarch64__)
-  static constexpr const char* kAlternatePathToLinker = "/system/bin/arm64/linker64";
-#elif defined (__arm__)
-  static constexpr const char* kAlternatePathToLinker = "/system/bin/arm/linker";
-#elif defined (__x86_64__)
-  static constexpr const char* kAlternatePathToLinker = "/system/bin/x86_64/linker64";
-#elif defined (__i386__)
-  static constexpr const char* kAlternatePathToLinker = "/system/bin/x86/linker";
-#else
-#error "Unknown architecture"
-#endif
+static constexpr const char* kPathToLinker = "/system/bin/" LINKER_NAME;
+static constexpr const char* kAlternatePathToLinker = "/system/bin/" ABI_STRING "/" LINKER_NAME;
+#undef LINKER_NAME
 
 const char* PathToLinker() {
   // On the systems with emulated architecture linker would be of different
diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp
index 940e726..c5d1218 100644
--- a/tests/dlfcn_test.cpp
+++ b/tests/dlfcn_test.cpp
@@ -33,6 +33,7 @@
 #include <thread>
 
 #include <android-base/file.h>
+#include <android-base/macros.h>
 #include <android-base/scopeguard.h>
 
 #include "gtest_globals.h"
@@ -966,17 +967,7 @@
 #endif
 }
 
-#if defined (__aarch64__)
-#define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib64/arm64/"
-#elif defined (__arm__)
-#define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib/arm/"
-#elif defined (__i386__)
-#define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib/x86/"
-#elif defined (__x86_64__)
-#define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib64/x86_64/"
-#else
-#error "Unknown architecture"
-#endif
+#define ALTERNATE_PATH_TO_SYSTEM_LIB "/system/lib64/" ABI_STRING "/"
 #define PATH_TO_LIBC PATH_TO_SYSTEM_LIB "libc.so"
 #define PATH_TO_BOOTSTRAP_LIBC PATH_TO_SYSTEM_LIB "bootstrap/libc.so"
 #define ALTERNATE_PATH_TO_LIBC ALTERNATE_PATH_TO_SYSTEM_LIB "libc.so"
diff --git a/tests/fenv_test.cpp b/tests/fenv_test.cpp
index c5b5eca..9cf9d98 100644
--- a/tests/fenv_test.cpp
+++ b/tests/fenv_test.cpp
@@ -117,6 +117,21 @@
   ASSERT_EQ(FE_OVERFLOW, fetestexcept(FE_ALL_EXCEPT));
 }
 
+TEST(fenv, fegetenv_fesetenv_rounding_mode) {
+  // Test that fegetenv()/fesetenv() includes the rounding mode.
+  fesetround(FE_DOWNWARD);
+  ASSERT_EQ(FE_DOWNWARD, fegetround());
+
+  fenv_t env;
+  fegetenv(&env);
+
+  fesetround(FE_UPWARD);
+  ASSERT_EQ(FE_UPWARD, fegetround());
+
+  fesetenv(&env);
+  ASSERT_EQ(FE_DOWNWARD, fegetround());
+}
+
 TEST(fenv, feholdexcept_feupdateenv) {
   // Set FE_OVERFLOW only.
   feclearexcept(FE_ALL_EXCEPT);
@@ -187,9 +202,10 @@
 
 TEST(fenv, feenableexcept_fegetexcept) {
 #if !defined(ANDROID_HOST_MUSL)
-#if defined(__aarch64__) || defined(__arm__)
-  // ARM doesn't support this. They used to if you go back far enough, but it was removed in
-  // the Cortex-A8 between r3p1 and r3p2.
+#if defined(__aarch64__) || defined(__arm__) || defined(__riscv)
+  // ARM and RISC-V don't support hardware trapping of floating point
+  // exceptions. ARM used to if you go back far enough, but it was
+  // removed in the Cortex-A8 between r3p1 and r3p2. RISC-V never has.
   ASSERT_EQ(-1, feenableexcept(FE_INVALID));
   ASSERT_EQ(0, fegetexcept());
   ASSERT_EQ(-1, feenableexcept(FE_DIVBYZERO));
@@ -200,8 +216,10 @@
   ASSERT_EQ(0, fegetexcept());
   ASSERT_EQ(-1, feenableexcept(FE_INEXACT));
   ASSERT_EQ(0, fegetexcept());
+#if defined(_FE_DENORMAL)  // riscv64 doesn't support this.
   ASSERT_EQ(-1, feenableexcept(FE_DENORMAL));
   ASSERT_EQ(0, fegetexcept());
+#endif
 #else
   // We can't recover from SIGFPE, so sacrifice a child...
   pid_t pid = fork();
diff --git a/tests/grp_pwd_test.cpp b/tests/grp_pwd_test.cpp
index bf65720..65a54a6 100644
--- a/tests/grp_pwd_test.cpp
+++ b/tests/grp_pwd_test.cpp
@@ -441,6 +441,17 @@
     }
     return result;
   };
+
+  // AID_PRNG_SEEDER (1092) was added in TM-QPR2, but CTS is shared
+  // across Android 13 versions so we may or may not find it in this
+  // test (b/253185870).
+  if (android::base::GetIntProperty("ro.build.version.sdk", 0) == __ANDROID_API_T__) {
+#ifndef AID_PRNG_SEEDER
+#define AID_PRNG_SEEDER 1092
+#endif
+    ids.erase(AID_PRNG_SEEDER);
+    expected_ids.erase(AID_PRNG_SEEDER);
+  }
   EXPECT_EQ(expected_ids, ids) << return_differences();
 }
 #endif
diff --git a/tests/headers/posix/sys_stat_h.c b/tests/headers/posix/sys_stat_h.c
index b22e34f..a299426 100644
--- a/tests/headers/posix/sys_stat_h.c
+++ b/tests/headers/posix/sys_stat_h.c
@@ -69,7 +69,7 @@
   STRUCT_MEMBER(struct stat, struct timespec, st_mtim);
   STRUCT_MEMBER(struct stat, struct timespec, st_ctim);
 #if defined(__BIONIC__)
-#if defined(__aarch64__)
+#if defined(__aarch64__) || defined(__riscv)
   STRUCT_MEMBER(struct stat, int, st_blksize);
 #elif defined(__x86_64__)
   STRUCT_MEMBER(struct stat, long, st_blksize);
diff --git a/tests/math_test.cpp b/tests/math_test.cpp
index 76b5078..60872f3 100644
--- a/tests/math_test.cpp
+++ b/tests/math_test.cpp
@@ -1053,22 +1053,22 @@
   auto guard = android::base::make_scope_guard([]() { fesetenv(FE_DFL_ENV); });
 
   fesetround(FE_UPWARD); // lrint/lrintf/lrintl obey the rounding mode.
-  ASSERT_EQ(1235, lrint(1234.01));
-  ASSERT_EQ(1235, lrintf(1234.01f));
-  ASSERT_EQ(1235, lrintl(1234.01L));
+  EXPECT_EQ(1235, lrint(1234.01));
+  EXPECT_EQ(1235, lrintf(1234.01f));
+  EXPECT_EQ(1235, lrintl(1234.01L));
   fesetround(FE_TOWARDZERO); // lrint/lrintf/lrintl obey the rounding mode.
-  ASSERT_EQ(1234, lrint(1234.01));
-  ASSERT_EQ(1234, lrintf(1234.01f));
-  ASSERT_EQ(1234, lrintl(1234.01L));
+  EXPECT_EQ(1234, lrint(1234.01));
+  EXPECT_EQ(1234, lrintf(1234.01f));
+  EXPECT_EQ(1234, lrintl(1234.01L));
 
   fesetround(FE_UPWARD); // llrint/llrintf/llrintl obey the rounding mode.
-  ASSERT_EQ(1235L, llrint(1234.01));
-  ASSERT_EQ(1235L, llrintf(1234.01f));
-  ASSERT_EQ(1235L, llrintl(1234.01L));
+  EXPECT_EQ(1235L, llrint(1234.01));
+  EXPECT_EQ(1235L, llrintf(1234.01f));
+  EXPECT_EQ(1235L, llrintl(1234.01L));
   fesetround(FE_TOWARDZERO); // llrint/llrintf/llrintl obey the rounding mode.
-  ASSERT_EQ(1234L, llrint(1234.01));
-  ASSERT_EQ(1234L, llrintf(1234.01f));
-  ASSERT_EQ(1234L, llrintl(1234.01L));
+  EXPECT_EQ(1234L, llrint(1234.01));
+  EXPECT_EQ(1234L, llrintf(1234.01f));
+  EXPECT_EQ(1234L, llrintl(1234.01L));
 }
 
 TEST(MATH_TEST, rint) {
diff --git a/tests/setjmp_test.cpp b/tests/setjmp_test.cpp
index 472aa20..2f891ec 100644
--- a/tests/setjmp_test.cpp
+++ b/tests/setjmp_test.cpp
@@ -81,8 +81,10 @@
     sigset64_t ss;
     sigemptyset64(&ss);
     sigaddset64(&ss, SIGUSR1 + offset);
+#if defined(__BIONIC__)
     // TIMER_SIGNAL.
     sigaddset64(&ss, __SIGRTMIN);
+#endif
     sigaddset64(&ss, SIGRTMIN + offset);
     return ss;
   }
@@ -224,13 +226,15 @@
 }
 
 #if defined(__arm__)
-#define __JB_SIGFLAG 0
+#define JB_SIGFLAG_OFFSET 0
 #elif defined(__aarch64__)
-#define __JB_SIGFLAG 0
+#define JB_SIGFLAG_OFFSET 0
 #elif defined(__i386__)
-#define __JB_SIGFLAG 8
+#define JB_SIGFLAG_OFFSET 8
+#elif defined(__riscv)
+#define JB_SIGFLAG_OFFSET 0
 #elif defined(__x86_64)
-#define __JB_SIGFLAG 8
+#define JB_SIGFLAG_OFFSET 8
 #endif
 
 TEST_F(setjmp_DeathTest, setjmp_cookie) {
@@ -238,7 +242,7 @@
   int value = setjmp(jb);
   ASSERT_EQ(0, value);
 
-  long* sigflag = reinterpret_cast<long*>(jb) + __JB_SIGFLAG;
+  long* sigflag = reinterpret_cast<long*>(jb) + JB_SIGFLAG_OFFSET;
 
   // Make sure there's actually a cookie.
   EXPECT_NE(0, *sigflag & ~1);
diff --git a/tests/signal_test.cpp b/tests/signal_test.cpp
index 5bda8b3..7f7f3db 100644
--- a/tests/signal_test.cpp
+++ b/tests/signal_test.cpp
@@ -34,6 +34,13 @@
 
 using namespace std::chrono_literals;
 
+#if defined(ANDROID_HOST_MUSL)
+// Musl doesn't export __SIGRTMIN and __SIGRTMAX, #define
+// them here.
+#define __SIGRTMIN 32
+#define __SIGRTMAX 64
+#endif
+
 static int SIGNAL_MIN() {
   return 1; // Signals start at 1 (SIGHUP), not 0.
 }
diff --git a/tests/stdio_test.cpp b/tests/stdio_test.cpp
index 21b3f6c..acc7ccd 100644
--- a/tests/stdio_test.cpp
+++ b/tests/stdio_test.cpp
@@ -490,22 +490,22 @@
 
   // NaN.
 
-  snprintf_fn(buf, sizeof(buf), fmt, nanf(""));
+  snprintf_fn(buf, sizeof(buf), fmt, nan(""));
   EXPECT_STREQ(nan_, buf) << fmt;
   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
   EXPECT_TRUE(isnan(f));
 
-  snprintf_fn(buf, sizeof(buf), fmt, -nanf(""));
+  snprintf_fn(buf, sizeof(buf), fmt, -nan(""));
   EXPECT_STREQ(minus_nan, buf) << fmt;
   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
   EXPECT_TRUE(isnan(f));
 
-  snprintf_fn(buf, sizeof(buf), fmt_plus, nanf(""));
+  snprintf_fn(buf, sizeof(buf), fmt_plus, nan(""));
   EXPECT_STREQ(plus_nan, buf) << fmt_plus;
   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
   EXPECT_TRUE(isnan(f));
 
-  snprintf_fn(buf, sizeof(buf), fmt_plus, -nanf(""));
+  snprintf_fn(buf, sizeof(buf), fmt_plus, -nan(""));
   EXPECT_STREQ(minus_nan, buf) << fmt_plus;
   EXPECT_EQ(1, sscanf_fn(buf, fmt, &f));
   EXPECT_TRUE(isnan(f));
diff --git a/tests/string_test.cpp b/tests/string_test.cpp
index 30c87dc..38957e2 100644
--- a/tests/string_test.cpp
+++ b/tests/string_test.cpp
@@ -136,7 +136,7 @@
   // A real-time signal.
   ASSERT_STREQ("Real-time signal 14", strsignal(SIGRTMIN + 14));
   // One of the signals the C library keeps to itself.
-  ASSERT_STREQ("Unknown signal 32", strsignal(__SIGRTMIN));
+  ASSERT_STREQ("Unknown signal 32", strsignal(32));  // __SIGRTMIN
 
   // Errors.
   ASSERT_STREQ("Unknown signal -1", strsignal(-1)); // Too small.