Added Posix Shell implementation of Runfiles. (#49)

This change adds `runfiles.sh`, the runfiles library in POSIX shell, and
makes `runfiles.bash` a thin wrapper that sources it. One implementation
serves both the existing `bazel_tools/tools/bash/runfiles/runfiles.bash`
snippets and scripts that run under dash, ash or busybox sh. The public
API is unchanged: `rlocation`, `runfiles_export_envvars`,
`runfiles_current_repository` and `runfiles_rlocation_checked`.

## Under bash

Nothing changes for callers. The caller's repository comes from
`BASH_SOURCE`, the functions are exported with `export -f`, and the
`use_bash_launcher` launcher keeps working.

## Under any other shell

Every script sources the library itself, since functions cannot be
exported across `exec`, and `runfiles_current_repository "$0"` takes the
script's path, since there is no `BASH_SOURCE`. A launcher that runs
under a non-bash `sh_toolchain` follows in #78.

## Initialization snippet v4

One snippet body serves both entry points: it resolves the library's
location before sourcing it instead of sourcing each candidate in turn,
and aborts the script if the library fails to load rather than leaving
it without `rlocation`. The bash and POSIX versions differ only in the
path they look for and in `pipefail`, which not every shell has. The
launcher uses the bash one; v3 keeps working.

## Performance

Lookups against a runfiles directory are one `stat`. Lookups against a
manifest use one `awk` process per lookup when awk is available (`AWK`
names the program), so the cost does not grow with the manifest; without
awk, or with `RULES_SHELL_RUNFILES_USE_AWK=0`, a shell loop searches
instead and nothing is forked. The snippets find the library the same
way. `shell/runfiles/README.md` has the details and a table produced by
`bazel run //tests/runfiles:benchmark`.

## Compatibility

The library needs Bazel 7.4 for its root symlinks; on Bazel 7 the
`//shell/runfiles` alias still resolves to Bazel's bundled library.

---

# Usage

## 1. Depend on the runfiles library from your build rule

```python
sh_binary(
    name = "my_binary",
    # ...
    deps = ["@rules_shell//shell/runfiles"],
)
```

## 2. Source the runfiles library

The library defines `rlocation`, which you would need to look up its own
location, so insert a snippet at the top of your main script. Bash
scripts:

```shell
# --- begin runfiles.bash initialization v4 ---
# Copy-pasted from the Bazel Bash runfiles library v4.
set -uo pipefail; set +e; f=bazel_tools/tools/bash/runfiles/runfiles.bash; _rf_p=; _rf_a=
if [ -n "${AWK:-}" ] || [ "${RULES_SHELL_RUNFILES_USE_AWK:-}" != 0 ]; then _rf_a=1; fi
_rf_d() { [ -f "$1/$f" ] && _rf_p="$1/$f"; }
_rf_m() { [ -f "$1" ] || return 1; if [ -n "$_rf_a" ]; then \
  _rf_p=$(${AWK:-awk} -v k="$f " 'index($0,k)==1{print substr($0,length(k)+1);m=1;exit}END{exit !m}' "$1" 2>/dev/null) && return; fi; \
  while IFS= read -r _rf_l || [ -n "$_rf_l" ]; do \
  case "$_rf_l" in "$f "*) _rf_p="${_rf_l#"$f "}"; return;; esac; done < "$1"; return 1; }
_rf_d "${RUNFILES_DIR:-/dev/null}" || _rf_m "${RUNFILES_MANIFEST_FILE:-/dev/null}" || \
  _rf_d "$0.runfiles" || _rf_m "$0.runfiles_manifest" || _rf_m "$0.exe.runfiles_manifest" || \
  { echo>&2 "ERROR: cannot find $f"; exit 1; }
# shellcheck disable=SC1090
. "$_rf_p" || { echo>&2 "ERROR: cannot source $_rf_p"; exit 1; }; f=; unset -f _rf_d _rf_m; unset _rf_l _rf_p _rf_a; set -e
# --- end runfiles.bash initialization v4 ---
```

POSIX shell scripts:

```shell
# --- begin runfiles.sh initialization v4 ---
# Copy-pasted from the Bazel POSIX shell runfiles library v4.
set -u; set +e; f=rules_shell/shell/runfiles/runfiles.sh; _rf_p=; _rf_a=
if [ -n "${AWK:-}" ] || [ "${RULES_SHELL_RUNFILES_USE_AWK:-}" != 0 ]; then _rf_a=1; fi
_rf_d() { [ -f "$1/$f" ] && _rf_p="$1/$f"; }
_rf_m() { [ -f "$1" ] || return 1; if [ -n "$_rf_a" ]; then \
  _rf_p=$(${AWK:-awk} -v k="$f " 'index($0,k)==1{print substr($0,length(k)+1);m=1;exit}END{exit !m}' "$1" 2>/dev/null) && return; fi; \
  while IFS= read -r _rf_l || [ -n "$_rf_l" ]; do \
  case "$_rf_l" in "$f "*) _rf_p="${_rf_l#"$f "}"; return;; esac; done < "$1"; return 1; }
_rf_d "${RUNFILES_DIR:-/dev/null}" || _rf_m "${RUNFILES_MANIFEST_FILE:-/dev/null}" || \
  _rf_d "$0.runfiles" || _rf_m "$0.runfiles_manifest" || _rf_m "$0.exe.runfiles_manifest" || \
  { echo>&2 "ERROR: cannot find $f"; exit 1; }
# shellcheck disable=SC1090
. "$_rf_p" || { echo>&2 "ERROR: cannot source $_rf_p"; exit 1; }; f=; unset -f _rf_d _rf_m; unset _rf_l _rf_p _rf_a; set -e
# --- end runfiles.sh initialization v4 ---
```

## 3. Use `rlocation` to look up runfile paths

```shell
cat "$(rlocation my_workspace/path/to/my/data.txt)"
```

---------

Co-authored-by: Fabian Meumertzheim <fabian@meumertzhe.im>
diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
index 6bec873..8b59eaf 100644
--- a/.bazelci/presubmit.yml
+++ b/.bazelci/presubmit.yml
@@ -5,7 +5,9 @@
 matrix:
   platform:
     - ubuntu2004
+    - ubuntu2004_arm64
     - macos
+    - macos_arm64
     - windows
   legacy_bazel:
     - 7.*
@@ -62,3 +64,22 @@
       - "//tests/..."
     test_targets:
       - "//tests/..."
+  test_posix_shell_runfiles:
+    # Dash coverage for the POSIX shell runfiles library. The suite runs under
+    # its own `#!/bin/sh`, which is dash on this image, not under the
+    # sh_toolchain, so no toolchain flag is involved. Local repro on a
+    # Debian-based host: bazel test //tests/runfiles:runfiles_sh_test
+    name: "POSIX Runfiles (dash, ${{modern_bazel}})"
+    bazel: ${{ modern_bazel }}
+    platform: ubuntu2004
+    shell_commands:
+      - "/bin/dash -c 'echo dash ready'"
+    build_targets:
+      - "//tests/runfiles:runfiles_sh_test"
+      - "//tests/runfiles:runfiles_sh_no_awk_test"
+    test_flags:
+      # Fail rather than pass under bash if /bin/sh on the CI image ever changes.
+      - "--test_env=RUNFILES_TEST_REQUIRE_POSIX_SH=1"
+    test_targets:
+      - "//tests/runfiles:runfiles_sh_test"
+      - "//tests/runfiles:runfiles_sh_no_awk_test"
diff --git a/.bcr/presubmit.yml b/.bcr/presubmit.yml
index f0aafac..a25822c 100644
--- a/.bcr/presubmit.yml
+++ b/.bcr/presubmit.yml
@@ -6,6 +6,7 @@
       - debian10
       - ubuntu2004
       - macos
+      - macos_arm64
       - windows
     bazel: [6.*, 7.*, 8.*, 9.*, 10.*]
   tasks:
diff --git a/MODULE.bazel b/MODULE.bazel
index 4fa13cb..fa509ea 100644
--- a/MODULE.bazel
+++ b/MODULE.bazel
@@ -12,7 +12,7 @@
 
 register_toolchains("@local_config_shell//:all")
 
-bazel_dep(name = "rules_shellcheck", version = "0.6.2", dev_dependency = True)
+bazel_dep(name = "rules_shellcheck", version = "0.6.4", dev_dependency = True)
 bazel_dep(name = "rules_testing", version = "0.9.0", dev_dependency = True)
 bazel_dep(name = "stardoc", version = "0.8.1", dev_dependency = True)
 bazel_dep(name = "with_cfg.bzl", version = "0.14.1", dev_dependency = True)
diff --git a/shell/private/sh_executable.bzl b/shell/private/sh_executable.bzl
index dba20d9..d16183d 100644
--- a/shell/private/sh_executable.bzl
+++ b/shell/private/sh_executable.bzl
@@ -21,6 +21,36 @@
 _SH_TOOLCHAIN_TYPE = Label("//shell:toolchain_type")
 _LAUNCHER_MAKER_TOOLCHAIN_TYPE = Label("@bazel_tools//tools/launcher:launcher_maker_toolchain_type")
 
+# The root symlink under which //shell/runfiles installs runfiles.bash; see
+# shell/runfiles/README.md.
+_RUNFILES_INIT_PATH = "bazel_tools/tools/bash/runfiles/runfiles.bash"
+
+# The launcher for `use_bash_launcher = True`: the v4 initialization snippet of
+# runfiles.bash, after which the runfiles variables and functions are exported
+# and the script exec'd.
+_LAUNCHER_TEMPLATE = """\
+{shebang}
+
+# --- begin runfiles.bash initialization v4 ---
+set -uo pipefail; set +e; f={init_path}; _rf_p=; _rf_a=
+if [ -n "${{AWK:-}}" ] || [ "${{RULES_SHELL_RUNFILES_USE_AWK:-}}" != 0 ]; then _rf_a=1; fi
+_rf_d() {{ [ -f "$1/$f" ] && _rf_p="$1/$f"; }}
+_rf_m() {{ [ -f "$1" ] || return 1; if [ -n "$_rf_a" ]; then \
+  _rf_p=$(${{AWK:-awk}} -v k="$f " 'index($0,k)==1{{print substr($0,length(k)+1);m=1;exit}}END{{exit !m}}' < "$1" 2>/dev/null); case $? in 0) return;; 1) return 1;; esac; fi; \
+  while IFS= read -r _rf_l || [ -n "$_rf_l" ]; do \
+  case "$_rf_l" in "$f "*) _rf_p="${{_rf_l#"$f "}}"; return;; esac; done < "$1"; return 1; }}
+_rf_d "${{RUNFILES_DIR:-/dev/null}}" || _rf_m "${{RUNFILES_MANIFEST_FILE:-/dev/null}}" || \
+  _rf_d "$0.runfiles" || _rf_m "$0.runfiles_manifest" || _rf_m "$0.exe.runfiles_manifest" || \
+  {{ echo>&2 "ERROR: cannot find $f"; exit 1; }}
+# shellcheck disable=SC1090
+. "$_rf_p" || {{ echo>&2 "ERROR: cannot source $_rf_p"; exit 1; }}; f=; unset -f _rf_d _rf_m; unset _rf_l _rf_p _rf_a; set -e
+# --- end runfiles.bash initialization v4 ---
+
+runfiles_export_envvars
+
+exec "$(rlocation "{src}")" "$@"
+"""
+
 def _to_rlocation_path(ctx, file):
     if file.short_path.startswith("../"):
         return file.short_path[3:]
@@ -52,24 +82,9 @@
             shebang = "#!{}".format(shell)
         ctx.actions.write(
             entrypoint,
-            content = """{shebang}
-
-# --- begin runfiles.bash initialization v3 ---
-set -uo pipefail; set +e; f=bazel_tools/tools/bash/runfiles/runfiles.bash
-# shellcheck disable=SC1090
-source "${{RUNFILES_DIR:-/dev/null}}/$f" 2>/dev/null || \
-  source "$(grep -sm1 "^$f " "${{RUNFILES_MANIFEST_FILE:-/dev/null}}" | cut -f2- -d' ')" 2>/dev/null || \
-  source "$0.runfiles/$f" 2>/dev/null || \
-  source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
-  source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
-  {{ echo>&2 "ERROR: cannot find $f"; exit 1; }}; f=; set -e
-# --- end runfiles.bash initialization v3 ---
-
-runfiles_export_envvars
-
-exec "$(rlocation "{src}")" "$@"
-""".format(
+            content = _LAUNCHER_TEMPLATE.format(
                 shebang = shebang,
+                init_path = _RUNFILES_INIT_PATH,
                 src = _to_rlocation_path(ctx, src),
             ),
             is_executable = True,
diff --git a/shell/runfiles/BUILD b/shell/runfiles/BUILD
index 63e6fee..d936f4e 100644
--- a/shell/runfiles/BUILD
+++ b/shell/runfiles/BUILD
@@ -1,6 +1,19 @@
 load("//shell:sh_library.bzl", "sh_library")
 load("//shell/private:root_symlinks.bzl", "ROOT_SYMLINKS_SUPPORTED", "root_symlinks")
 
+# The runfiles library. There is one implementation, runfiles.sh, reachable
+# under two names in the runfiles tree:
+#
+# - bazel_tools/tools/bash/runfiles/runfiles.bash, the path the bash
+#   initialization snippets and the launcher source. It is a thin wrapper
+#   that sources runfiles.sh.
+# - rules_shell/shell/runfiles/runfiles.sh, the path the POSIX initialization
+#   snippet sources, for scripts that run under any POSIX shell.
+#
+# Both are root symlinks, which need the `skip_conflict_checking` parameter
+# added in Bazel 7.4.0. Where the native shell rules still exist (Bazel 7) the
+# alias keeps resolving to the library bundled with Bazel, as it always has,
+# and runfiles.sh is not installed.
 alias(
     name = "runfiles",
     actual = ":runfiles_impl" if ROOT_SYMLINKS_SUPPORTED else "@bazel_tools//tools/bash/runfiles",
@@ -9,19 +22,51 @@
 
 sh_library(
     name = "runfiles_impl",
-    data = [":runfiles_at_legacy_location"],
+    data = [
+        ":runfiles_at_legacy_location",
+        ":runfiles_sh_at_documented_location",
+    ],
     tags = ["manual"],
 )
 
+# runfiles.bash locates runfiles.sh next to itself, so the two are installed
+# side by side at the legacy location, as they are in the source tree.
 root_symlinks(
     name = "runfiles_at_legacy_location",
     root_symlinks = {
         "runfiles.bash": "bazel_tools/tools/bash/runfiles/runfiles.bash",
+        "runfiles.sh": "bazel_tools/tools/bash/runfiles/runfiles.sh",
     },
     tags = ["manual"],
 )
 
+# runfiles.sh at the path the POSIX init snippet uses
+# (`f=rules_shell/shell/runfiles/runfiles.sh`). Its natural path starts with
+# this repository's canonical name (`rules_shell+/...`, or `_main/...` when it
+# is the main repository), which a copy-pasted snippet cannot know, so the
+# symlink gives it one fixed path. It is also the rlocation path consumers see
+# for the file through the repository mapping.
+root_symlinks(
+    name = "runfiles_sh_at_documented_location",
+    root_symlinks = {
+        "runfiles.sh": "rules_shell/shell/runfiles/runfiles.sh",
+    },
+    tags = ["manual"],
+)
+
+# runfiles.sh on its own, under its natural path, for the test suites to source
+# the POSIX library directly.
+sh_library(
+    name = "runfiles_sh",
+    srcs = ["runfiles.sh"],
+    tags = ["manual"],
+    visibility = ["//tests/runfiles:__pkg__"],
+)
+
 exports_files(
-    ["runfiles.bash"],
+    [
+        "runfiles.bash",
+        "runfiles.sh",
+    ],
     visibility = ["//tests/runfiles:__pkg__"],
 )
diff --git a/shell/runfiles/README.md b/shell/runfiles/README.md
new file mode 100644
index 0000000..6dba3e3
--- /dev/null
+++ b/shell/runfiles/README.md
@@ -0,0 +1,59 @@
+# Runfiles library
+
+`runfiles.sh` is the runfiles library for `sh_binary` and `sh_test` scripts,
+written in POSIX shell. `runfiles.bash` is a thin wrapper that sources it, for
+bash scripts and for the `bazel_tools/tools/bash/runfiles/runfiles.bash`
+initialization snippets they already carry. Both expose the same public API:
+`rlocation`, `runfiles_export_envvars`, `runfiles_current_repository` and
+`runfiles_rlocation_checked`. The header of each file documents its
+initialization snippet and the environment variables it reads.
+
+Under bash the library behaves the way the bash library always has: the
+caller's repository is detected from `BASH_SOURCE`, and the functions are
+exported with `export -f`, which is how the `use_bash_launcher` launcher makes
+them available to a script without a snippet. Under any other shell neither is
+possible: `runfiles_current_repository` needs the caller's script path as its
+argument, `rlocation` without a second argument assumes the main repository,
+and every script sources the library itself.
+
+## What a lookup costs
+
+A lookup served from a runfiles directory is one `stat`. A lookup served from
+a manifest has to search it. Which of the two a script gets is not a property
+of the platform: the manifest is used whenever `RUNFILES_MANIFEST_FILE` names
+an existing file. On Linux a sandboxed `bazel test` sees only `RUNFILES_DIR`;
+`bazel run`, a directly executed binary and everything on Windows go through
+the manifest. Either way, when the binary has a repository mapping, the
+apparent repository name is first resolved through it, which is a search of
+that file, and under bash with a manifest one more search of the manifest finds
+the calling script's repository. Nothing else is forked: the library's helpers
+store their results in variables rather than printing them.
+
+The library searches with `awk` when awk can be found (`AWK` names the
+program, `awk` from `PATH` otherwise), one process per search. awk reads the
+file in bulk, so the cost of a search does not grow with the file.
+With `RULES_SHELL_RUNFILES_USE_AWK=0`, or on a host without awk, a shell
+`read` loop searches instead, at 10 to 45 µs per line: a lookup then costs in
+proportion to how far down the manifest its key sits, and a miss costs two
+passes, one for the key and one for its directory prefixes. Nothing is forked
+in that mode. The initialization snippets find the library the same way.
+
+## Measurements
+
+`bazel run //tests/runfiles:benchmark` generates manifests with keys shaped
+like a pip dependency's, times a script that sources the library and resolves
+keys spread through them, and prints this table. `--baseline FILE` adds a
+column for another `runfiles.bash`; here it is the library before this one,
+`git show 660e16c:shell/runfiles/runfiles.bash`. Measured on one Linux machine
+with bash 5.2, dash as `sh` and gawk 5.2, best of 3.
+
+| manifest | baseline | `runfiles.bash` | `runfiles.sh`, bash | `runfiles.sh`, sh | `runfiles.sh`, sh, no awk |
+|---|---|---|---|---|---|
+| 5000 lines, 5 keys spread through it | 79 ms | 22 ms | 21 ms | 13 ms | 317 ms |
+| 20000 lines, 5 keys spread through it | 81 ms | 27 ms | 29 ms | 19 ms | 1.1 s |
+| 50000 lines, 5 keys spread through it | 87 ms | 37 ms | 37 ms | 29 ms | 2.6 s |
+| 5000 lines, 1 key near the top | 21 ms | 7 ms | 7 ms | 4 ms | 2 ms |
+| runfiles directory, 1 key | 3 ms | 3 ms | 3 ms | 2 ms | 1 ms |
+
+50 keys spread through the 50000-line manifest: 347 ms through `runfiles.bash`,
+7.2 s with the shell loops under bash.
diff --git a/shell/runfiles/runfiles.bash b/shell/runfiles/runfiles.bash
index 5b08416..8ece2a0 100644
--- a/shell/runfiles/runfiles.bash
+++ b/shell/runfiles/runfiles.bash
@@ -12,9 +12,23 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-# Runfiles lookup library for Bazel-built Bash binaries and tests, version 3.
+# Runfiles lookup library for Bazel-built Bash binaries and tests, version 4.
+#
+# This file is the bash entry point to the runfiles library. The implementation
+# is runfiles.sh, next to this file, which this file sources; README.md in this
+# directory describes both.
 #
 # VERSION HISTORY:
+# - version 4: The init code resolves the library's location before sourcing
+#              it, instead of sourcing each candidate location in turn.
+#   Features:
+#     - Errors the library prints while it is sourced are no longer hidden,
+#       and a library that fails to load aborts the script.
+#     - The manifest is searched with awk, or a shell loop, instead of grep
+#       and cut.
+#   Compatibility:
+#     - The init script and the runfiles library are backwards and forwards
+#       compatible with versions 2 and 3.
 # - version 3: Fixes a bug in the init code on macOS and makes the library aware
 #              of Bzlmod repository mappings.
 #   Features:
@@ -51,6 +65,7 @@
 # ENVIRONMENT:
 # - If RUNFILES_LIB_DEBUG=1 is set, the script will print diagnostic messages to
 #   stderr.
+# - AWK and RULES_SHELL_RUNFILES_USE_AWK, see runfiles.sh.
 #
 # USAGE:
 # 1.  Depend on this runfiles library from your build rule:
@@ -67,17 +82,21 @@
 #     up the library's runtime location, thus we have a chicken-and-egg problem.
 #     Insert the following code snippet to the top of your main script:
 #
-#       # --- begin runfiles.bash initialization v3 ---
-#       # Copy-pasted from the Bazel Bash runfiles library v3.
-#       set -uo pipefail; set +e; f=bazel_tools/tools/bash/runfiles/runfiles.bash
+#       # --- begin runfiles.bash initialization v4 ---
+#       # Copy-pasted from the Bazel Bash runfiles library v4.
+#       set -uo pipefail; set +e; f=bazel_tools/tools/bash/runfiles/runfiles.bash; _rf_p=; _rf_a=
+#       if [ -n "${AWK:-}" ] || [ "${RULES_SHELL_RUNFILES_USE_AWK:-}" != 0 ]; then _rf_a=1; fi
+#       _rf_d() { [ -f "$1/$f" ] && _rf_p="$1/$f"; }
+#       _rf_m() { [ -f "$1" ] || return 1; if [ -n "$_rf_a" ]; then \
+#         _rf_p=$(${AWK:-awk} -v k="$f " 'index($0,k)==1{print substr($0,length(k)+1);m=1;exit}END{exit !m}' < "$1" 2>/dev/null); case $? in 0) return;; 1) return 1;; esac; fi; \
+#         while IFS= read -r _rf_l || [ -n "$_rf_l" ]; do \
+#         case "$_rf_l" in "$f "*) _rf_p="${_rf_l#"$f "}"; return;; esac; done < "$1"; return 1; }
+#       _rf_d "${RUNFILES_DIR:-/dev/null}" || _rf_m "${RUNFILES_MANIFEST_FILE:-/dev/null}" || \
+#         _rf_d "$0.runfiles" || _rf_m "$0.runfiles_manifest" || _rf_m "$0.exe.runfiles_manifest" || \
+#         { echo>&2 "ERROR: cannot find $f"; exit 1; }
 #       # shellcheck disable=SC1090
-#       source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || \
-#         source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || \
-#         source "$0.runfiles/$f" 2>/dev/null || \
-#         source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
-#         source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
-#         { echo>&2 "ERROR: cannot find $f"; exit 1; }; f=; set -e
-#       # --- end runfiles.bash initialization v3 ---
+#       . "$_rf_p" || { echo>&2 "ERROR: cannot source $_rf_p"; exit 1; }; f=; unset -f _rf_d _rf_m; unset _rf_l _rf_p _rf_a; set -e
+#       # --- end runfiles.bash initialization v4 ---
 #
 #
 # 3.  Use rlocation to look up runfile paths.
@@ -87,506 +106,22 @@
 # You can skip steps 1 and 2 when setting "use_bash_launcher" attribute in sh_binary or sh_test.
 #
 
-if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
-  if [[ -f "$0.runfiles_manifest" ]]; then
-    export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
-  elif [[ -f "$0.runfiles/MANIFEST" ]]; then
-    export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
-  elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
-    export RUNFILES_DIR="$0.runfiles"
-  fi
+# runfiles.sh is installed next to this file wherever this file is: in the
+# source tree, and under bazel_tools/tools/bash/runfiles/ in a runfiles
+# directory (see //shell/runfiles:runfiles_at_legacy_location). A manifest
+# entry for this file points at the source tree, so the same holds there.
+_rf_bash_dir="${BASH_SOURCE[0]%/*}"
+[[ "$_rf_bash_dir" == "${BASH_SOURCE[0]}" ]] && _rf_bash_dir=.
+# A missing runfiles.sh fails the source the way a missing runfiles.bash does.
+# The message is visible with the v4 snippet and the launcher; the v3 snippet
+# redirects stderr.
+if [[ ! -f "$_rf_bash_dir/runfiles.sh" ]]; then
+  echo >&2 "ERROR[runfiles.bash]: cannot find runfiles.sh next to ${BASH_SOURCE[0]}"
+  unset _rf_bash_dir
+  return 1
 fi
 
-case "$(uname -s | tr '[:upper:]' '[:lower:]')" in
-msys*|mingw*|cygwin*)
-  # matches an absolute Windows path
-  export _RLOCATION_ISABS_PATTERN="^[a-zA-Z]:[/\\]"
-  # Windows paths are case insensitive and Bazel and MSYS2 capitalize differently, so we can't
-  # assume that all paths are in the same native case.
-  export _RLOCATION_GREP_CASE_INSENSITIVE_ARGS=-i
-  ;;
-*)
-  # matches an absolute Unix path
-  export _RLOCATION_ISABS_PATTERN="^/[^/].*"
-  export _RLOCATION_GREP_CASE_INSENSITIVE_ARGS=
-  ;;
-esac
+# shellcheck disable=SC1091
+source "$_rf_bash_dir/runfiles.sh"
 
-# Does not exit with a non-zero exit code if no match is found and performs a case-insensitive
-# search on Windows.
-function __runfiles_maybe_grep() {
-  # The GREP_XXX variables influence how grep behaves. Specifically, they can
-  # affect the output from the grep command.
-  GREP_COLOR="" GREP_OPTIONS="" grep $_RLOCATION_GREP_CASE_INSENSITIVE_ARGS "$@" || test $? = 1;
-}
-export -f __runfiles_maybe_grep
-
-# Escape the argument for use in a grep regex.
-# This is used to escape paths that may contain special characters.
-function __runfiles_escape_grep() {
-  echo -n "$1" | sed 's/[.[\*^$]/\\&/g'
-}
-export -f __runfiles_escape_grep
-
-# Lexically resolves the "." and ".." segments in the given rlocation path.
-# Fails if the path is empty or would escape the runfiles root.
-function __runfiles_normalize_rlocation_path() {
-  local rest="$1"
-  local normalized=
-  local segment
-  while [[ -n "$rest" ]]; do
-    if [[ "$rest" == */* ]]; then
-      segment="${rest%%/*}"
-      rest="${rest#*/}"
-    else
-      segment="$rest"
-      rest=
-    fi
-    case "$segment" in
-      "" | ".")
-        ;;
-      "..")
-        if [[ "$normalized" == */* ]]; then
-          normalized="${normalized%/*}"
-        elif [[ -n "$normalized" ]]; then
-          normalized=
-        else
-          return 1
-        fi
-        ;;
-      *)
-        normalized="${normalized:+$normalized/}$segment"
-        ;;
-    esac
-  done
-  [[ -n "$normalized" ]] || return 1
-  echo "$normalized"
-}
-export -f __runfiles_normalize_rlocation_path
-
-# Resolves the target of a runfiles manifest entry to a path in the local file system.
-#
-# Bazel stores the target of an unresolved symlink (ctx.actions.declare_symlink) in the manifest
-# verbatim, so unlike all other targets it may be a relative path. In a materialized runfiles
-# directory the entry is a symlink with that very target, which the file system resolves relative to
-# the directory containing the symlink. A relative target thus has to be interpreted as an rlocation
-# path relative to the directory of the entry and looked up in the manifest again.
-#
-# Arguments:
-#   $1: the rlocation path of the manifest entry
-#   $2: the target of the manifest entry
-#   $3: the path to append to the target, if any
-#   $4: the current lookup depth, used to break out of cycles of unresolved symlinks
-# Prints the resolved path if it exists and the empty string otherwise.
-function __runfiles_resolve_manifest_target() {
-  if [[ "$2" =~ $_RLOCATION_ISABS_PATTERN || "$2" == /* ]]; then
-    local -r resolved="$2$3"
-    if [[ -e "$resolved" ]]; then
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "INFO[runfiles.bash]: rlocation($1$3): found in manifest as ($resolved)"
-      fi
-      echo "$resolved"
-    else
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "INFO[runfiles.bash]: rlocation($1$3): found in manifest as ($resolved), but file does not exist"
-      fi
-      echo ""
-    fi
-    return 0
-  fi
-
-  local entry_dir="${1%/*}"
-  [[ "$entry_dir" == "$1" ]] && entry_dir=
-  local target_rlocation_path
-  target_rlocation_path=$(__runfiles_normalize_rlocation_path "${entry_dir:+$entry_dir/}$2$3") || {
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "ERROR[runfiles.bash]: rlocation($1$3): unresolved symlink target ($2) points outside the runfiles tree"
-    fi
-    echo ""
-    return 0
-  }
-  if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-    echo >&2 "INFO[runfiles.bash]: rlocation($1$3): unresolved symlink target ($2) resolves to ($target_rlocation_path)"
-  fi
-  runfiles_rlocation_checked "$target_rlocation_path" "$(($4 + 1))"
-}
-export -f __runfiles_resolve_manifest_target
-
-# Prints to stdout the runtime location of a data-dependency.
-# The optional second argument can be used to specify the canonical name of the
-# repository whose repository mapping should be used to resolve the repository
-# part of the provided path. If not specified, the repository of the caller is
-# used.
-function rlocation() {
-  if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-    echo >&2 "INFO[runfiles.bash]: rlocation($1): start"
-  fi
-  if [[ "$1" =~ $_RLOCATION_ISABS_PATTERN ]]; then
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "INFO[runfiles.bash]: rlocation($1): absolute path, return"
-    fi
-    # If the path is absolute, print it as-is.
-    echo "$1"
-    return 0
-  elif [[ "$1" == ../* || "$1" == */.. || "$1" == ./* || "$1" == */./* || "$1" == "*/." || "$1" == *//* ]]; then
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "ERROR[runfiles.bash]: rlocation($1): path is not normalized"
-    fi
-    return 1
-  elif [[ "$1" == \\* ]]; then
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "ERROR[runfiles.bash]: rlocation($1): absolute path without" \
-               "drive name"
-    fi
-    return 1
-  fi
-
-  if [[ -f "$RUNFILES_REPO_MAPPING" ]]; then
-    local -r target_repo_apparent_name=$(echo "$1" | cut -d / -f 1)
-    # Use -s to get an empty remainder if the argument does not contain a slash.
-    # The repo mapping should not be applied to single segment paths, which may
-    # be root symlinks.
-    local -r remainder=$(echo "$1" | cut -s -d / -f 2-)
-    if [[ -n "$remainder" ]]; then
-      if [[ -z "${2+x}" ]]; then
-        local -r source_repo=$(runfiles_current_repository 2)
-      else
-        local -r source_repo=$2
-      fi
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "INFO[runfiles.bash]: rlocation($1): looking up canonical name for ($target_repo_apparent_name) from ($source_repo) in ($RUNFILES_REPO_MAPPING)"
-      fi
-      # The repo mapping manifest may compactly represent the mapping for source
-      # repos of the form module++ext+<something> with rows of the form
-      # module++ext+*,module,module+. We don't want to rely on the particular
-      # separator char, but do assume that it is not a valid character in a
-      # user-specified repository name.
-      # If the source repo name does not match the sed pattern, then the
-      # alternative in the regex below will have identical branches, which is
-      # fine. The ^ is duplicated in each branch since grep doesn't support
-      # empty subexpressions.
-      local -r source_repo_prefix="$(echo -n "$source_repo" | sed 's/\(.*[^-a-zA-Z0-9_.]\)[-a-zA-Z0-9_.]\{1,\}/\1*/')"
-      local -r escaped_pattern="\(^$(__runfiles_escape_grep "$source_repo")\|^$(__runfiles_escape_grep "$source_repo_prefix")\),$(__runfiles_escape_grep "$target_repo_apparent_name"),"
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "INFO[runfiles.bash]: rlocation($1): matching pattern on repo mapping manifest ($escaped_pattern)"
-      fi
-      local -r target_repo=$(__runfiles_maybe_grep -m1 "$escaped_pattern" "$RUNFILES_REPO_MAPPING" | cut -d , -f 3)
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "INFO[runfiles.bash]: rlocation($1): canonical name of target repo is ($target_repo)"
-      fi
-      if [[ -n "$target_repo" ]]; then
-        local -r rlocation_path="$target_repo/$remainder"
-      else
-        local -r rlocation_path="$1"
-      fi
-    else
-      local -r rlocation_path="$1"
-    fi
-  else
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "INFO[runfiles.bash]: rlocation($1): not using repository mapping ($RUNFILES_REPO_MAPPING) since it does not exist"
-    fi
-    local -r rlocation_path="$1"
-  fi
-
-  runfiles_rlocation_checked "$rlocation_path"
-}
-export -f rlocation
-
-# Exports the environment variables that subprocesses need in order to use
-# runfiles.
-# If a subprocess is a Bazel-built binary rule that also uses the runfiles
-# libraries under @bazel_tools//tools/<lang>/runfiles, then that binary needs
-# these envvars in order to initialize its own runfiles library.
-function runfiles_export_envvars() {
-  if [[ ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" \
-        && ! -d "${RUNFILES_DIR:-/dev/null}" ]]; then
-    return 1
-  fi
-
-  if [[ ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
-    if [[ -f "$RUNFILES_DIR/MANIFEST" ]]; then
-      export RUNFILES_MANIFEST_FILE="$RUNFILES_DIR/MANIFEST"
-    elif [[ -f "${RUNFILES_DIR}_manifest" ]]; then
-      export RUNFILES_MANIFEST_FILE="${RUNFILES_DIR}_manifest"
-    else
-      export RUNFILES_MANIFEST_FILE=
-    fi
-  elif [[ ! -d "${RUNFILES_DIR:-/dev/null}" ]]; then
-    if [[ "$RUNFILES_MANIFEST_FILE" == */MANIFEST \
-          && -d "${RUNFILES_MANIFEST_FILE%/MANIFEST}" ]]; then
-      export RUNFILES_DIR="${RUNFILES_MANIFEST_FILE%/MANIFEST}"
-      export JAVA_RUNFILES="$RUNFILES_DIR"
-    elif [[ "$RUNFILES_MANIFEST_FILE" == *_manifest \
-          && -d "${RUNFILES_MANIFEST_FILE%_manifest}" ]]; then
-      export RUNFILES_DIR="${RUNFILES_MANIFEST_FILE%_manifest}"
-      export JAVA_RUNFILES="$RUNFILES_DIR"
-    else
-      export RUNFILES_DIR=
-    fi
-  fi
-}
-export -f runfiles_export_envvars
-
-# Returns the canonical name of the Bazel repository containing the script that
-# calls this function.
-# The optional argument N, which defaults to 1, can be used to return the
-# canonical name of the N-th caller instead.
-#
-# Note: This function only works correctly with Bzlmod enabled. Without Bzlmod,
-# its return value is ignored if passed to rlocation.
-# shellcheck disable=SC2001 # patterns are either too complex or contain slashes
-function runfiles_current_repository() {
-  local -r idx=${1:-1}
-  local -r raw_caller_path="${BASH_SOURCE[$idx]}"
-  # Make the caller path absolute if needed to handle the case where the script is run directly
-  # from bazel-bin, with working directory a subdirectory of bazel-bin.
-  if [[ "$raw_caller_path" =~ $_RLOCATION_ISABS_PATTERN ]]; then
-    local -r caller_path="$raw_caller_path"
-  else
-    local -r caller_path="$(cd "$(dirname "$raw_caller_path")" || return 1; pwd)/$(basename "$raw_caller_path")"
-  fi
-  if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-    echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): caller's path is ($caller_path)"
-  fi
-
-  local rlocation_path=
-
-  # If the runfiles manifest exists, search for an entry with target the caller's path.
-  if [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
-    # Escape $caller_path for use in the grep regex below. Also replace \ with / since the manifest
-    # uses / as the path separator even on Windows.
-    local -r normalized_caller_path="$(echo "$caller_path" | sed 's|\\\\*|/|g')"
-    local -r escaped_caller_path="$(__runfiles_escape_grep "$normalized_caller_path")"
-    rlocation_path=$(__runfiles_maybe_grep -m1 "^[^ ]* ${escaped_caller_path}$" "${RUNFILES_MANIFEST_FILE}" | cut -d ' ' -f 1)
-    if [[ -z "$rlocation_path" ]]; then
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "ERROR[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) is not the target of an entry in the runfiles manifest ($RUNFILES_MANIFEST_FILE)"
-      fi
-      # The binary may also be run directly from bazel-bin or bazel-out.
-      local -r repository=$(echo "$normalized_caller_path" | __runfiles_maybe_grep -E -o '(^|/)(bazel-out/[^/]+/bin|bazel-bin)/external/[^/]+/' | tail -1 | ${AWK:-awk} -F/ '{print $(NF-1)}')
-      if [[ -n "$repository" ]]; then
-        if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-          echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) lies in repository ($repository) (parsed exec path)"
-        fi
-        echo "$repository"
-      else
-        if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-          echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) lies in the main repository (parsed exec path)"
-        fi
-        echo ""
-      fi
-      return 1
-    else
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) is the target of ($rlocation_path) in the runfiles manifest"
-      fi
-    fi
-  fi
-
-  # If the runfiles directory exists, check if the caller's path is of the form
-  # $RUNFILES_DIR/rlocation_path and if so, set $rlocation_path.
-  if [[ -z "$rlocation_path" && -d "${RUNFILES_DIR:-/dev/null}" ]]; then
-    normalized_caller_path="$(echo "$caller_path" | sed 's|\\\\*|/|g')"
-    normalized_dir="$(echo "${RUNFILES_DIR%[\/]}" | sed 's|\\\\*|/|g')"
-    if [[ -n "${_RLOCATION_GREP_CASE_INSENSITIVE_ARGS}" ]]; then
-      # When comparing file paths insensitively, also normalize the case of the prefixes.
-      normalized_caller_path=$(echo "$normalized_caller_path" | tr '[:upper:]' '[:lower:]')
-      normalized_dir=$(echo "$normalized_dir" | tr '[:upper:]' '[:lower:]')
-    fi
-    if [[ "$normalized_caller_path" == "$normalized_dir"/* ]]; then
-      rlocation_path=${normalized_caller_path:${#normalized_dir}}
-      rlocation_path=${rlocation_path:1}
-    fi
-    if [[ -z "$rlocation_path" ]]; then
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) does not lie under the runfiles directory ($normalized_dir)"
-      fi
-      # The only shell script that is not executed from the runfiles directory (if it is populated)
-      # is the sh_binary entrypoint. Parse its path under the execroot, using the last match to
-      # allow for nested execroots (e.g. in Bazel integration tests). The binary may also be run
-      # directly from bazel-bin.
-      local -r repository=$(echo "$normalized_caller_path" | __runfiles_maybe_grep -E -o '(^|/)(bazel-out/[^/]+/bin|bazel-bin)/external/[^/]+/' | tail -1 | ${AWK:-awk} -F/ '{print $(NF-1)}')
-      if [[ -n "$repository" ]]; then
-        if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-          echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) lies in repository ($repository) (parsed exec path)"
-        fi
-        echo "$repository"
-      else
-        if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-          echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($normalized_caller_path) lies in the main repository (parsed exec path)"
-        fi
-        echo ""
-      fi
-      return 0
-    else
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($caller_path) has path ($rlocation_path) relative to the runfiles directory ($RUNFILES_DIR)"
-      fi
-    fi
-  fi
-
-  if [[ -z "$rlocation_path" ]]; then
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "ERROR[runfiles.bash]: runfiles_current_repository($idx): cannot determine repository for ($caller_path) since neither the runfiles directory (${RUNFILES_DIR:-}) nor the runfiles manifest (${RUNFILES_MANIFEST_FILE:-}) exist"
-    fi
-    return 1
-  fi
-
-  if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-    echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($caller_path) corresponds to rlocation path ($rlocation_path)"
-  fi
-  # Normalize the rlocation path to be of the form repo/pkg/file.
-  rlocation_path=${rlocation_path#_main/external/}
-  rlocation_path=${rlocation_path#_main/../}
-  local -r repository=$(echo "$rlocation_path" | cut -d / -f 1)
-  if [[ "$repository" == _main ]]; then
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($rlocation_path) lies in the main repository"
-    fi
-    echo ""
-  else
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "INFO[runfiles.bash]: runfiles_current_repository($idx): ($rlocation_path) lies in repository ($repository)"
-    fi
-    echo "$repository"
-  fi
-}
-export -f runfiles_current_repository
-
-function runfiles_rlocation_checked() {
-  # FIXME: If the runfiles lookup fails, the exit code of this function is 0 if
-  #  and only if the runfiles manifest exists. In particular, the exit code
-  #  behavior is not consistent across platforms.
-  # The optional second argument is the current lookup depth, which only differs from zero while
-  # following the target of an unresolved symlink.
-  local -r depth="${2:-0}"
-  if [[ "$depth" -gt 32 ]]; then
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "ERROR[runfiles.bash]: rlocation($1): too many levels of symbolic links"
-    fi
-    echo ""
-    return 0
-  fi
-  # The manifest takes precedence over the runfiles directory: whether the directory is populated
-  # is a property of the execution of the action or test, which is not known at analysis time, so
-  # the directory may exist but contain the stale contents of a previous execution. If the manifest
-  # exists, it is always authoritative.
-  if [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "INFO[runfiles.bash]: rlocation($1): looking in RUNFILES_MANIFEST_FILE ($RUNFILES_MANIFEST_FILE)"
-    fi
-    # If the rlocation path contains a space or newline, it needs to be prefixed
-    # with a space and spaces, newlines, and backslashes have to be escaped as
-    # \s, \n, and \b.
-    if [[ "$1" == *" "* || "$1" == *$'\n'* ]]; then
-      local search_prefix
-      search_prefix=" $(echo -n "$1" | sed 's/\\/\\b/g; s/ /\\s/g')"
-      search_prefix="${search_prefix//$'\n'/\\n}"
-      local escaped=true
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "INFO[runfiles.bash]: rlocation($1): using escaped search prefix ($search_prefix)"
-      fi
-    else
-      local search_prefix="$1"
-      local escaped=false
-    fi
-    # The extra space below is added because cut counts from 1.
-    local trim_length
-    trim_length=$(echo -n "$search_prefix  " | wc -c | tr -d ' ')
-    # Escape the search prefix for use in the grep regex below *after*
-    # determining the trim length.
-    local result
-    result=$(__runfiles_maybe_grep -m1 "^$(__runfiles_escape_grep "$search_prefix") " "${RUNFILES_MANIFEST_FILE}" | cut -b "${trim_length}-")
-    if [[ -z "$result" ]]; then
-      # If path references a runfile that lies under a directory that itself
-      # is a runfile, then only the directory is listed in the manifest. Look
-      # up all prefixes of path in the manifest and append the relative path
-      # from the prefix if there is a match.
-      local prefix="$1"
-      local prefix_result=
-      local new_prefix=
-      while true; do
-        new_prefix="${prefix%/*}"
-        [[ "$new_prefix" == "$prefix" ]] && break
-        prefix="$new_prefix"
-        if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-          echo >&2 "INFO[runfiles.bash]: rlocation($1): looking for prefix ($prefix)"
-        fi
-        if [[ "$prefix" == *" "* || "$prefix" == *$'\n'* ]]; then
-          search_prefix=" $(echo -n "$prefix" | sed 's/\\/\\b/g; s/ /\\s/g')"
-          search_prefix="${search_prefix//$'\n'/\\n}"
-          escaped=true
-          if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-            echo >&2 "INFO[runfiles.bash]: rlocation($1): using escaped search prefix ($search_prefix)"
-          fi
-        else
-          search_prefix="$prefix"
-          escaped=false
-        fi
-        # The extra space below is added because cut counts from 1.
-        trim_length=$(echo -n "$search_prefix  " | wc -c | tr -d ' ')
-        prefix_result=$(__runfiles_maybe_grep -m1 "^$(__runfiles_escape_grep "$search_prefix") " "${RUNFILES_MANIFEST_FILE}" | cut -b "${trim_length}"-)
-        if [[ "$escaped" = true ]]; then
-          prefix_result="${prefix_result//\\n/$'\n'}"
-          prefix_result="${prefix_result//\\b/\\}"
-        fi
-        [[ -z "$prefix_result" ]] && continue
-        if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-          echo >&2 "INFO[runfiles.bash]: rlocation($1): found in manifest via prefix ($prefix)"
-        fi
-        local candidate
-        # The trailing marker prevents command substitution from stripping a newline that is part
-        # of the resolved path.
-        candidate=$(__runfiles_resolve_manifest_target \
-            "$prefix" "$prefix_result" "${1#"${prefix}"}" "$depth"; echo -n x)
-        candidate="${candidate%$'\n'x}"
-        if [[ -n "$candidate" ]]; then
-          echo "$candidate"
-          return 0
-        fi
-        # At this point, the manifest lookup of prefix has been successful,
-        # but the file at the relative path given by the suffix does not
-        # exist. We do not continue the lookup with a shorter prefix for two
-        # reasons:
-        # 1. Manifests generated by Bazel never contain a path that is a
-        #    prefix of another path.
-        # 2. Runfiles libraries for other languages do not check for file
-        #    existence and would have returned the non-existent path. It seems
-        #    better to return no path rather than a potentially different,
-        #    non-empty path.
-        if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-          echo >&2 "INFO[runfiles.bash]: rlocation($1): prefix ($prefix) did not resolve, not retrying with a shorter one"
-        fi
-        break
-      done
-      if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-        echo >&2 "INFO[runfiles.bash]: rlocation($1): not found in manifest"
-      fi
-      echo ""
-    else
-      if [[ "$escaped" = true ]]; then
-        result="${result//\\n/$'\n'}"
-        result="${result//\\b/\\}"
-      fi
-      __runfiles_resolve_manifest_target "$1" "$result" "" "$depth"
-    fi
-  elif [[ -e "${RUNFILES_DIR:-/dev/null}/$1" ]]; then
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "INFO[runfiles.bash]: rlocation($1): found under RUNFILES_DIR ($RUNFILES_DIR), return"
-    fi
-    echo "${RUNFILES_DIR}/$1"
-  else
-    if [[ "${RUNFILES_LIB_DEBUG:-}" == 1 ]]; then
-      echo >&2 "ERROR[runfiles.bash]: cannot look up runfile \"$1\" " \
-               "(RUNFILES_DIR=\"${RUNFILES_DIR:-}\"," \
-               "RUNFILES_MANIFEST_FILE=\"${RUNFILES_MANIFEST_FILE:-}\")"
-    fi
-    return 1
-  fi
-}
-export -f runfiles_rlocation_checked
-
-# The repo mapping manifest may not exist with old versions of Bazel.
-RUNFILES_REPO_MAPPING=$(runfiles_rlocation_checked _repo_mapping || echo "")
-export RUNFILES_REPO_MAPPING
+unset _rf_bash_dir
diff --git a/shell/runfiles/runfiles.sh b/shell/runfiles/runfiles.sh
new file mode 100644
index 0000000..93660cf
--- /dev/null
+++ b/shell/runfiles/runfiles.sh
@@ -0,0 +1,1222 @@
+# shellcheck shell=sh
+# Copyright 2026 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Runfiles lookup library for Bazel-built shell binaries and tests, in POSIX
+# shell.
+#
+# This file is the implementation behind both @rules_shell//shell/runfiles
+# entry points. Sourced directly, it is the POSIX library; runfiles.bash, next
+# to it, is the bash entry point and sources it. The public API is
+# rlocation, runfiles_export_envvars, runfiles_current_repository and
+# runfiles_rlocation_checked. Under bash the caller's repository is detected
+# from BASH_SOURCE and the functions are exported with `export -f`. Under any
+# other shell, runfiles_current_repository needs the caller's script path as
+# its argument, rlocation without a second argument assumes the main
+# repository, and every script has to source the library itself.
+#
+# README.md in this directory covers what a lookup costs, with measurements.
+#
+# ENVIRONMENT
+#
+# Read when the library is sourced, so a setting has to be in the environment
+# by then: the rule's `env` attribute, --test_env / --action_env, or an export
+# before the initialization snippet.
+#
+# - RUNFILES_DIR, RUNFILES_MANIFEST_FILE: where the runfiles are, as set by
+#   Bazel or by a parent's runfiles_export_envvars; derived from $0 when
+#   neither is set. The manifest is used whenever it names an existing file.
+# - RUNFILES_LIB_DEBUG=1: print a diagnostic to stderr for every lookup.
+# - AWK: the awk program that searches manifests, one process per lookup;
+#   `awk` from PATH by default. Expanded unquoted, so `busybox awk` works. A
+#   program that cannot be found leaves the shell loops in place.
+# - RULES_SHELL_RUNFILES_USE_AWK=0: search manifests with shell loops rather
+#   than awk, so that nothing is forked. Has no effect when AWK is set.
+#
+# Exported for child processes: RUNFILES_DIR, RUNFILES_MANIFEST_FILE and
+# JAVA_RUNFILES (by runfiles_export_envvars), and RUNFILES_REPO_MAPPING, the
+# path of the repository mapping manifest.
+#
+# USAGE
+#
+# 1.  Depend on this runfiles library from your build rule:
+#
+#       sh_binary(
+#           name = "my_binary",
+#           ...
+#           deps = ["@rules_shell//shell/runfiles"],
+#       )
+#
+# 2.  Source the runfiles library. It defines rlocation, which you would need
+#     to look up its own location, so insert this snippet at the top of your
+#     main script:
+#
+#       # --- begin runfiles.sh initialization v4 ---
+#       # Copy-pasted from the Bazel POSIX shell runfiles library v4.
+#       set -u; set +e; f=rules_shell/shell/runfiles/runfiles.sh; _rf_p=; _rf_a=
+#       if [ -n "${AWK:-}" ] || [ "${RULES_SHELL_RUNFILES_USE_AWK:-}" != 0 ]; then _rf_a=1; fi
+#       _rf_d() { [ -f "$1/$f" ] && _rf_p="$1/$f"; }
+#       _rf_m() { [ -f "$1" ] || return 1; if [ -n "$_rf_a" ]; then \
+#         _rf_p=$(${AWK:-awk} -v k="$f " 'index($0,k)==1{print substr($0,length(k)+1);m=1;exit}END{exit !m}' < "$1" 2>/dev/null); case $? in 0) return;; 1) return 1;; esac; fi; \
+#         while IFS= read -r _rf_l || [ -n "$_rf_l" ]; do \
+#         case "$_rf_l" in "$f "*) _rf_p="${_rf_l#"$f "}"; return;; esac; done < "$1"; return 1; }
+#       _rf_d "${RUNFILES_DIR:-/dev/null}" || _rf_m "${RUNFILES_MANIFEST_FILE:-/dev/null}" || \
+#         _rf_d "$0.runfiles" || _rf_m "$0.runfiles_manifest" || _rf_m "$0.exe.runfiles_manifest" || \
+#         { echo>&2 "ERROR: cannot find $f"; exit 1; }
+#       # shellcheck disable=SC1090
+#       . "$_rf_p" || { echo>&2 "ERROR: cannot source $_rf_p"; exit 1; }; f=; unset -f _rf_d _rf_m; unset _rf_l _rf_p _rf_a; set -e
+#       # --- end runfiles.sh initialization v4 ---
+#
+#
+# 3.  Use rlocation to look up runfile paths.
+#
+#       cat "$(rlocation my_workspace/path/to/my/data.txt)"
+#
+
+# --- Initialization ---
+
+if ! [ -d "${RUNFILES_DIR:-/dev/null}" ] && ! [ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]; then
+  if [ -f "$0.runfiles_manifest" ]; then
+    export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
+  elif [ -f "$0.runfiles/MANIFEST" ]; then
+    export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
+  # The library under either name //shell/runfiles installs it as: a tree
+  # that only has the legacy bazel_tools one, as Bazel's own runfiles target
+  # builds it, is a runfiles directory all the same.
+  elif [ -f "$0.runfiles/rules_shell/shell/runfiles/runfiles.sh" ] \
+    || [ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]; then
+    export RUNFILES_DIR="$0.runfiles"
+  fi
+fi
+
+# Detects whether we are running in a Windows shell environment (MSYS2, MinGW
+# or Cygwin) and sets _RLOCATION_ISABS_WINDOWS / _RLOCATION_CASE_INSENSITIVE
+# accordingly, from the environment and shell builtins.
+#
+# Signals, in order of reliability:
+#   1. MSYSTEM is set by every MSYS2, MinGW and Git-for-Windows shell.
+#   2. OSTYPE is set by bash to "cygwin" / "msys" (absent under dash).
+#   3. /proc/version names the runtime on Cygwin and MSYS2 ("CYGWIN_NT-...",
+#      "MSYS_NT-...", "MINGW64_NT-..."). If the file exists and does not name
+#      one of those, we are on a Unix-like system and must not consult the
+#      Windows environment variables below; WSL, for instance, can inherit
+#      WINDIR from the host through WSLENV.
+#   4. Only when there is no /proc at all (so, not Linux and not Cygwin/MSYS)
+#      do WINDIR / SystemRoot indicate a Windows environment.
+#
+# $1 optionally overrides the /proc/version path so that the Windows branches
+# can be covered by tests on non-Windows hosts.
+__runfiles_detect_platform() {
+  _rf_dp_procver_file="${1:-/proc/version}"
+  _rf_dp_win=
+  _rf_dp_line=
+
+  if [ -n "${MSYSTEM:-}" ]; then
+    _rf_dp_win=1
+  else
+    # OSTYPE is a bash variable and simply expands to the empty string under a
+    # POSIX shell, which is why it is read through ${OSTYPE:-}. Consulting it
+    # costs nothing and catches a Cygwin bash that has no MSYSTEM and no /proc.
+    # shellcheck disable=SC3028
+    case "${OSTYPE:-}" in
+      cygwin*|msys*|win32*) _rf_dp_win=1 ;;
+    esac
+  fi
+
+  if [ -z "$_rf_dp_win" ]; then
+    if [ -r "$_rf_dp_procver_file" ]; then
+      IFS= read -r _rf_dp_line < "$_rf_dp_procver_file" || :
+      case "$_rf_dp_line" in
+        *CYGWIN*|*Cygwin*|*cygwin*|*MSYS*|*Msys*|*msys*|*MINGW*|*Mingw*|*mingw*)
+          _rf_dp_win=1
+          ;;
+      esac
+    elif [ -n "${WINDIR:-}${SystemRoot:-}${SYSTEMROOT:-}" ]; then
+      _rf_dp_win=1
+    fi
+  fi
+
+  if [ -n "$_rf_dp_win" ]; then
+    export _RLOCATION_ISABS_WINDOWS=1
+    export _RLOCATION_CASE_INSENSITIVE=1
+  else
+    export _RLOCATION_ISABS_WINDOWS=
+    export _RLOCATION_CASE_INSENSITIVE=
+  fi
+
+  _rf_dp_procver_file=
+  _rf_dp_win=
+  _rf_dp_line=
+}
+
+__runfiles_detect_platform
+
+# Literal newline for use in case patterns and string comparisons.
+_RULES_SHELL_RUNFILES_NL='
+'
+export _RULES_SHELL_RUNFILES_NL
+
+# --- Internal helper functions ---
+
+# Print a diagnostic to stderr under RUNFILES_LIB_DEBUG=1. Written as an `if`
+# rather than `[ ... ] && echo`, so that it never returns 1 into a caller's
+# `set -e`.
+__runfiles_debug() {
+  if [ "${RUNFILES_LIB_DEBUG:-}" = 1 ]; then
+    echo >&2 "$@"
+  fi
+}
+
+# Returns 0 if $1 is an absolute path, 1 otherwise.
+__runfiles_is_abs() {
+  case "$1" in
+    /[!/]*) return 0 ;;
+  esac
+  if [ -n "$_RLOCATION_ISABS_WINDOWS" ]; then
+    case "$1" in
+      # Spelled out rather than written as ranges: bash before 5.0 collates
+      # bracket ranges by locale, so [a-z] can match characters outside ASCII.
+      [ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]:[/\\]*) return 0 ;;
+    esac
+  fi
+  return 1
+}
+
+# Replace one or more consecutive backslashes with a single forward slash, into
+# _rf_nb_out. Stored rather than printed so that finding the caller's
+# repository, which rlocation does on every lookup under bash, forks nothing.
+# Equivalent to: sed 's|\\\\*|/|g'
+__runfiles_normalize_backslashes() {
+  _rf_nb_in="$1"
+  _rf_nb_out=""
+  _rf_nb_bs=false
+  while [ -n "$_rf_nb_in" ]; do
+    _rf_nb_c="${_rf_nb_in%"${_rf_nb_in#?}"}"
+    _rf_nb_in="${_rf_nb_in#?}"
+    case "$_rf_nb_c" in
+      "\\")
+        if [ "$_rf_nb_bs" = false ]; then
+          _rf_nb_out="${_rf_nb_out}/"
+          _rf_nb_bs=true
+        fi
+        ;;
+      *)
+        _rf_nb_bs=false
+        _rf_nb_out="${_rf_nb_out}${_rf_nb_c}"
+        ;;
+    esac
+  done
+}
+
+# Replace all occurrences of $2 in $1 with $3, into _rf_gs_out. Stored rather
+# than printed so that encoding and decoding escaped manifest keys, which take
+# several passes, do not fork per pass.
+# Equivalent to: ${1//$2/$3} (bash-only).
+__runfiles_gsub() {
+  _rf_gs_in="$1"
+  _rf_gs_old="$2"
+  _rf_gs_new="$3"
+  _rf_gs_out=""
+  # An empty needle would loop forever: `*""*` matches unconditionally and the
+  # parameter expansion strips nothing.
+  if [ -z "$_rf_gs_old" ]; then
+    _rf_gs_out="$_rf_gs_in"
+    return 0
+  fi
+  while :; do
+    case "$_rf_gs_in" in
+      *"$_rf_gs_old"*)
+        _rf_gs_out="${_rf_gs_out}${_rf_gs_in%%"$_rf_gs_old"*}${_rf_gs_new}"
+        _rf_gs_in="${_rf_gs_in#*"$_rf_gs_old"}"
+        ;;
+      *)
+        _rf_gs_out="${_rf_gs_out}${_rf_gs_in}"
+        break
+        ;;
+    esac
+  done
+}
+
+# Compute the wildcard prefix for repo mapping lookups, into _rf_cp_out.
+# Replaces the rightmost run of safe chars ([-a-zA-Z0-9_.]) that follows a
+# separator (non-safe char) with `*`, preserving any trailing non-safe chars.
+# Leaves the input unchanged when there is no non-safe-followed-by-safe pair
+# (e.g. `rules_shell+`, `protobuf+`, and other bzlmod module root names).
+# Equivalent to: sed 's/\(.*[^-a-zA-Z0-9_.]\)[-a-zA-Z0-9_.]\{1,\}/\1*/'
+#
+# The result is stored rather than printed so that rlocation does not fork a
+# subshell for it on every lookup.
+__runfiles_compute_repo_prefix() {
+  _rf_cp_repo="$1"
+  # Phase 1: peel any trailing non-safe chars into $suffix. Sed keeps these
+  # after the star (e.g. `my_module++ext+` -> `my_module++*+`).
+  _rf_cp_suffix=""
+  _rf_cp_head="$_rf_cp_repo"
+  while [ -n "$_rf_cp_head" ]; do
+    _rf_cp_last="${_rf_cp_head#"${_rf_cp_head%?}"}"
+    case "$_rf_cp_last" in
+      [-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.]) break ;;
+      *)
+        _rf_cp_suffix="${_rf_cp_last}${_rf_cp_suffix}"
+        _rf_cp_head="${_rf_cp_head%?}"
+        ;;
+    esac
+  done
+  # Phase 2: peel the trailing safe run off $head. We only need to know
+  # whether we stripped at least one safe char (sed requires ≥1).
+  _rf_cp_stripped_safe=0
+  while [ -n "$_rf_cp_head" ]; do
+    _rf_cp_last="${_rf_cp_head#"${_rf_cp_head%?}"}"
+    case "$_rf_cp_last" in
+      [-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.])
+        _rf_cp_stripped_safe=1
+        _rf_cp_head="${_rf_cp_head%?}"
+        ;;
+      *) break ;;
+    esac
+  done
+  # Sed requires BOTH ≥1 safe chars AND a non-safe char before them.
+  if [ "$_rf_cp_stripped_safe" -eq 0 ] || [ -z "$_rf_cp_head" ]; then
+    _rf_cp_out="$_rf_cp_repo"
+    return 0
+  fi
+  _rf_cp_out="${_rf_cp_head}*${_rf_cp_suffix}"
+}
+
+# --- Manifest search ---
+
+# Convert ASCII uppercase to lowercase, into _rf_tl_out. Stored rather than
+# printed so that no caller forks for it: the case-insensitive manifest scans
+# call it once per line.
+__runfiles_tolower() {
+  _rf_tl_in="$1"
+  _rf_tl_out=""
+  while [ -n "$_rf_tl_in" ]; do
+    _rf_tl_c="${_rf_tl_in%"${_rf_tl_in#?}"}"
+    _rf_tl_in="${_rf_tl_in#?}"
+    case "$_rf_tl_c" in
+      A) _rf_tl_c=a;; B) _rf_tl_c=b;; C) _rf_tl_c=c;; D) _rf_tl_c=d;;
+      E) _rf_tl_c=e;; F) _rf_tl_c=f;; G) _rf_tl_c=g;; H) _rf_tl_c=h;;
+      I) _rf_tl_c=i;; J) _rf_tl_c=j;; K) _rf_tl_c=k;; L) _rf_tl_c=l;;
+      M) _rf_tl_c=m;; N) _rf_tl_c=n;; O) _rf_tl_c=o;; P) _rf_tl_c=p;;
+      Q) _rf_tl_c=q;; R) _rf_tl_c=r;; S) _rf_tl_c=s;; T) _rf_tl_c=t;;
+      U) _rf_tl_c=u;; V) _rf_tl_c=v;; W) _rf_tl_c=w;; X) _rf_tl_c=x;;
+      Y) _rf_tl_c=y;; Z) _rf_tl_c=z;;
+    esac
+    _rf_tl_out="${_rf_tl_out}${_rf_tl_c}"
+  done
+}
+
+# Return 0 iff the first ${#2} characters of $1, lowercased, equal $2, which
+# must already be lowercase: a prefix test that stops at the first mismatch
+# rather than folding the whole line.
+__runfiles_line_starts_with_ci() {
+  _rf_lsw_line="$1"
+  _rf_lsw_lpfx="$2"
+  while [ -n "$_rf_lsw_lpfx" ]; do
+    [ -z "$_rf_lsw_line" ] && return 1
+    _rf_lsw_pc="${_rf_lsw_lpfx%"${_rf_lsw_lpfx#?}"}"
+    _rf_lsw_lpfx="${_rf_lsw_lpfx#?}"
+    _rf_lsw_lc="${_rf_lsw_line%"${_rf_lsw_line#?}"}"
+    _rf_lsw_line="${_rf_lsw_line#?}"
+    case "$_rf_lsw_lc" in
+      A) _rf_lsw_lc=a;; B) _rf_lsw_lc=b;; C) _rf_lsw_lc=c;; D) _rf_lsw_lc=d;;
+      E) _rf_lsw_lc=e;; F) _rf_lsw_lc=f;; G) _rf_lsw_lc=g;; H) _rf_lsw_lc=h;;
+      I) _rf_lsw_lc=i;; J) _rf_lsw_lc=j;; K) _rf_lsw_lc=k;; L) _rf_lsw_lc=l;;
+      M) _rf_lsw_lc=m;; N) _rf_lsw_lc=n;; O) _rf_lsw_lc=o;; P) _rf_lsw_lc=p;;
+      Q) _rf_lsw_lc=q;; R) _rf_lsw_lc=r;; S) _rf_lsw_lc=s;; T) _rf_lsw_lc=t;;
+      U) _rf_lsw_lc=u;; V) _rf_lsw_lc=v;; W) _rf_lsw_lc=w;; X) _rf_lsw_lc=x;;
+      Y) _rf_lsw_lc=y;; Z) _rf_lsw_lc=z;;
+    esac
+    [ "$_rf_lsw_lc" != "$_rf_lsw_pc" ] && return 1
+  done
+  return 0
+}
+
+# Manifests are searched with awk rather than a shell `read` loop whenever awk
+# can be found: a fork per lookup, but one that reads the file in bulk, so the
+# cost stops growing with the manifest. AWK names the program, `awk` on PATH
+# otherwise, and is expanded unquoted where it runs.
+# RULES_SHELL_RUNFILES_USE_AWK=0 keeps the shell loops, which fork nothing.
+_RULES_SHELL_RUNFILES_AWK=
+if [ -n "${AWK:-}" ] || [ "${RULES_SHELL_RUNFILES_USE_AWK:-}" != 0 ]; then
+  _RULES_SHELL_RUNFILES_AWK="${AWK:-awk}"
+  if ! command -v "${_RULES_SHELL_RUNFILES_AWK%% *}" >/dev/null 2>&1; then
+    __runfiles_debug "WARNING[runfiles.sh]: '$_RULES_SHELL_RUNFILES_AWK' cannot be found; searching manifests with shell loops"
+    _RULES_SHELL_RUNFILES_AWK=
+  fi
+fi
+export _RULES_SHELL_RUNFILES_AWK
+
+# Run the awk program $1 over the file $2. Every further argument is a
+# parameter, which the program reads from ARGV[1], ARGV[2], ... in its BEGIN
+# block and blanks, so that awk reads the file from stdin instead. The file is
+# redirected rather than passed as an operand because awk takes an operand of
+# the form name=value as an assignment. Parameters travel as arguments rather
+# than through `-v`, which would process the backslashes of an escaped key.
+#
+# awk runs in the C locale: a path is a byte string, gawk warns on stderr about
+# bytes that are not valid in a UTF-8 locale, and ASCII-only case folding is
+# what the shell loops do too.
+__runfiles_awk() {
+  _rf_aw_prog="$1"
+  _rf_aw_file="$2"
+  shift 2
+  LC_ALL=C $_RULES_SHELL_RUNFILES_AWK "$_rf_aw_prog" "$@" < "$_rf_aw_file"
+}
+
+# Find the first line in $2 whose key is exactly $1 and store the value
+# (everything after the key and the separating space) in _rf_fl_val.
+# $1 must already be in manifest (escaped) form.
+# On Windows (_RLOCATION_CASE_INSENSITIVE=1), matching is case-insensitive
+# but the value is returned with its original casing.
+#
+# The result is stored rather than printed so that callers do not fork a
+# subshell per lookup.
+__runfiles_find_line() {
+  _rf_fl_val=
+
+  if [ -n "${_RULES_SHELL_RUNFILES_AWK:-}" ]; then
+    __runfiles_find_line_awk "$1" "$2"
+  else
+    __runfiles_find_line_scan "$1" "$2"
+  fi
+}
+
+# The awk search behind __runfiles_find_line.
+__runfiles_find_line_awk() {
+  _rf_fl_val=$(__runfiles_awk '
+    BEGIN { k = ARGV[1]; c = ARGV[2]; ARGV[1] = ARGV[2] = ""
+            n = length(k); if (c) k = tolower(k) }
+    { h = substr($0, 1, n); if (c) h = tolower(h)
+      if (h == k) { print substr($0, n + 1); f = 1; exit } }
+    END { exit !f }' "$2" "$1 " "$_RLOCATION_CASE_INSENSITIVE")
+}
+
+# The shell-loop search behind __runfiles_find_line: a single quoted `case`
+# rejects a line, and nothing is copied out of one until it matches.
+__runfiles_find_line_scan() {
+  _rf_fl_pfx_sp="$1 "
+  if [ -n "$_RLOCATION_CASE_INSENSITIVE" ]; then
+    __runfiles_tolower "$_rf_fl_pfx_sp"
+    _rf_fl_lpfx="$_rf_tl_out"
+    _rf_fl_plen=${#_rf_fl_pfx_sp}
+    while IFS= read -r _rf_fl_line || [ -n "$_rf_fl_line" ]; do
+      if __runfiles_line_starts_with_ci "$_rf_fl_line" "$_rf_fl_lpfx"; then
+        _rf_fl_val="$_rf_fl_line"
+        _rf_fl_i=0
+        while [ "$_rf_fl_i" -lt "$_rf_fl_plen" ]; do
+          _rf_fl_val="${_rf_fl_val#?}"
+          _rf_fl_i=$((_rf_fl_i + 1))
+        done
+        return 0
+      fi
+    done < "$2"
+  else
+    while IFS= read -r _rf_fl_line || [ -n "$_rf_fl_line" ]; do
+      case "$_rf_fl_line" in
+        "${_rf_fl_pfx_sp}"*)
+          _rf_fl_val="${_rf_fl_line#"${_rf_fl_pfx_sp}"}"
+          return 0
+          ;;
+      esac
+    done < "$2"
+  fi
+  return 1
+}
+
+# Find the entry in $2 for the longest proper `/`-separated path prefix of the
+# rlocation path $1. This resolves a file that is only reachable through a
+# directory runfile, since a manifest lists the directory and not its contents.
+#
+# Resolving every prefix in one pass matters: a scan is a `read` loop costing
+# microseconds per line, and one pass per candidate prefix would multiply that
+# by the depth of the path.
+#
+# Comparison happens in the manifest's own (escaped) domain, so that no line
+# has to be decoded during the scan; only the winning entry is decoded, by the
+# caller. On Windows matching is case-insensitive but values are returned with
+# their original casing.
+#
+# Args: $1=rlocation path $2=manifest $3=escaped form of $1
+#       $4=non-empty iff $1 has to be looked up in escaped form
+# Sets:
+#   _rf_fp_val     the matched value, still escaped
+#   _rf_fp_esc     non-empty iff the matched entry was an escaped one
+#   _rf_fp_suffix  the part of $1 below the matched key, to append to the value
+# Returns 1 if no prefix matched.
+__runfiles_find_prefix() {
+  _rf_fp_path="$1"
+  _rf_fp_epath="$3"
+  _rf_fp_want_esc="$4"
+  _rf_fp_val=
+  _rf_fp_esc=
+  _rf_fp_suffix=
+  _rf_fp_key=
+
+  if [ -n "${_RULES_SHELL_RUNFILES_AWK:-}" ]; then
+    __runfiles_find_prefix_awk "$2" || return 1
+  else
+    __runfiles_find_prefix_scan "$2" || return 1
+  fi
+
+  # The matched key is a prefix of the escaped path, so the suffix is the rest
+  # of that path. `/` is never escaped, so cutting the escaped form at a
+  # segment boundary and decoding what follows yields the unescaped suffix;
+  # without an escaped lookup the two forms are the same string. On a
+  # case-insensitive platform the key may differ from the path in case, so it
+  # is cut by length rather than by pattern.
+  if [ -n "$_RLOCATION_CASE_INSENSITIVE" ]; then
+    _rf_fp_suffix="$_rf_fp_epath"
+    _rf_fp_n=${#_rf_fp_key}
+    while [ "$_rf_fp_n" -gt 0 ]; do
+      _rf_fp_suffix="${_rf_fp_suffix#?}"
+      _rf_fp_n=$((_rf_fp_n - 1))
+    done
+  else
+    _rf_fp_suffix="${_rf_fp_epath#"$_rf_fp_key"}"
+  fi
+  if [ -n "$_rf_fp_want_esc" ]; then
+    __runfiles_gsub "$_rf_fp_suffix" '\n' "$_RULES_SHELL_RUNFILES_NL"
+    __runfiles_gsub "$_rf_gs_out" '\s' ' '
+    __runfiles_gsub "$_rf_gs_out" '\b' '\'
+    _rf_fp_suffix="$_rf_gs_out"
+  fi
+  return 0
+}
+
+# The awk search behind __runfiles_find_prefix: one pass applies the same rules
+# as the scan and reports the escaped flag, key and value on three lines.
+__runfiles_find_prefix_awk() {
+  _rf_fp_out=$(__runfiles_awk '
+    BEGIN { p = ARGV[1]; e = ARGV[2]; c = ARGV[3]; ARGV[1] = ARGV[2] = ARGV[3] = ""
+            if (c) p = tolower(p); best = 0 }
+    { esc = (substr($0, 1, 1) == " ")
+      if (esc && e == "") next
+      line = esc ? substr($0, 2) : $0
+      i = index(line, " "); if (i == 0) next
+      n = i - 1
+      if (n <= best || n >= length(p)) next
+      k = substr(line, 1, n)
+      if ((c ? tolower(k) : k) != substr(p, 1, n) || substr(p, n + 1, 1) != "/") next
+      v = substr(line, i + 1); if (v == "") next
+      best = n; bk = k; bv = v; be = esc }
+    END { if (!best) exit 1; if (be) print "1"; else print ""; print bk; print bv }' \
+    "$1" "$_rf_fp_epath" "$_rf_fp_want_esc" "$_RLOCATION_CASE_INSENSITIVE") || return 1
+  _rf_fp_esc="${_rf_fp_out%%"$_RULES_SHELL_RUNFILES_NL"*}"
+  _rf_fp_out="${_rf_fp_out#*"$_RULES_SHELL_RUNFILES_NL"}"
+  _rf_fp_key="${_rf_fp_out%%"$_RULES_SHELL_RUNFILES_NL"*}"
+  _rf_fp_val="${_rf_fp_out#*"$_RULES_SHELL_RUNFILES_NL"}"
+}
+
+# The shell-loop search behind __runfiles_find_prefix. The loop body runs once
+# per manifest line, so everything that is not needed to reject a line is
+# deferred, in particular the value, which is never copied out of a line that
+# does not match. The reject is a single quoted `case`: a manifest key can only
+# be a prefix of the path if the path starts with it.
+__runfiles_find_prefix_scan() {
+  _rf_fp_klen=0
+  if [ -n "$_RLOCATION_CASE_INSENSITIVE" ]; then
+    __runfiles_tolower "$_rf_fp_epath"
+    _rf_fp_lepath="$_rf_tl_out"
+  fi
+  while IFS= read -r _rf_fp_line || [ -n "$_rf_fp_line" ]; do
+    _rf_fp_k="${_rf_fp_line%% *}"
+    if [ -z "$_rf_fp_k" ]; then
+      # Leading space: an escaped entry, or a blank line.
+      [ -n "$_rf_fp_want_esc" ] || continue
+      _rf_fp_k="${_rf_fp_line# }"
+      _rf_fp_k="${_rf_fp_k%% *}"
+      [ -n "$_rf_fp_k" ] || continue
+      _rf_fp_this_esc=1
+    else
+      _rf_fp_this_esc=
+    fi
+    if [ -n "$_RLOCATION_CASE_INSENSITIVE" ]; then
+      # Folding the key is one builtin operation under bash 4 and a loop over
+      # its characters elsewhere; either way nothing is forked per line.
+      __runfiles_tolower "$_rf_fp_k"
+      _rf_fp_cmp="$_rf_tl_out"
+      _rf_fp_against="$_rf_fp_lepath"
+    else
+      _rf_fp_cmp="$_rf_fp_k"
+      _rf_fp_against="$_rf_fp_epath"
+    fi
+    case "$_rf_fp_against" in
+      "$_rf_fp_cmp"*) ;;
+      *) continue ;;
+    esac
+
+    # Past this point the line is a genuine candidate, so the rest of the work
+    # is off the hot path.
+    #
+    # The key has to end on a path separator: `c/dir` is a prefix of
+    # `c/dir/file` but not of `c/dirx/file`.
+    case "$_rf_fp_against" in
+      "$_rf_fp_cmp"/*) ;;
+      *) continue ;;
+    esac
+    # Only a longer key than the best one so far can win.
+    [ "${#_rf_fp_k}" -gt "$_rf_fp_klen" ] || continue
+    case "$_rf_fp_line" in *" "*) ;; *) continue ;; esac
+    if [ -n "$_rf_fp_this_esc" ]; then
+      _rf_fp_v="${_rf_fp_line# }"
+      _rf_fp_v="${_rf_fp_v#* }"
+    else
+      _rf_fp_v="${_rf_fp_line#* }"
+    fi
+    # An entry with an empty value is treated as absent: it does not stop the
+    # walk up the path prefixes.
+    [ -n "$_rf_fp_v" ] || continue
+    _rf_fp_key="$_rf_fp_k"
+    _rf_fp_klen=${#_rf_fp_k}
+    _rf_fp_val="$_rf_fp_v"
+    _rf_fp_esc="$_rf_fp_this_esc"
+  done < "$1"
+  [ -n "$_rf_fp_key" ]
+}
+
+# Find the first non-escaped manifest line whose value (target path) matches
+# $1 and store its key (rlocation path) in _rf_ft_out; returns 1 if there is
+# none. On Windows, matching is case-insensitive.
+__runfiles_find_by_target() {
+  _rf_ft_target="$1"
+  _rf_ft_file="$2"
+  _rf_ft_out=
+
+  if [ -n "${_RULES_SHELL_RUNFILES_AWK:-}" ]; then
+    _rf_ft_out=$(__runfiles_awk '
+      BEGIN { t = ARGV[1]; c = ARGV[2]; ARGV[1] = ARGV[2] = ""; if (c) t = tolower(t) }
+      substr($0, 1, 1) == " " { next }
+      { i = index($0, " "); if (i == 0) next
+        v = substr($0, i + 1); if (c) v = tolower(v)
+        if (v == t) { printf "%s", substr($0, 1, i - 1); f = 1; exit } }
+      END { exit !f }' "$_rf_ft_file" "$_rf_ft_target" "$_RLOCATION_CASE_INSENSITIVE") || return 1
+    return 0
+  fi
+
+  if [ -n "$_RLOCATION_CASE_INSENSITIVE" ]; then
+    __runfiles_tolower "$_rf_ft_target"
+    _rf_ft_ltgt="$_rf_tl_out"
+    _rf_ft_tlen=${#_rf_ft_target}
+    while IFS= read -r _rf_ft_line || [ -n "$_rf_ft_line" ]; do
+      case "$_rf_ft_line" in " "*) continue ;; esac
+      _rf_ft_key="${_rf_ft_line%% *}"
+      _rf_ft_val="${_rf_ft_line#* }"
+      # Cheap length check first — avoids per-char lowercasing when lengths
+      # can't match.
+      [ "${#_rf_ft_val}" = "$_rf_ft_tlen" ] || continue
+      if __runfiles_line_starts_with_ci "$_rf_ft_val" "$_rf_ft_ltgt"; then
+        _rf_ft_out="$_rf_ft_key"
+        return 0
+      fi
+    done < "$_rf_ft_file"
+  else
+    while IFS= read -r _rf_ft_line || [ -n "$_rf_ft_line" ]; do
+      # One quoted `case` rejects the ~all lines that do not match, without
+      # copying anything out of them. A non-escaped entry contains exactly one
+      # space, so ending in " $target" is the same test as its value being
+      # $target; the split below re-checks it regardless.
+      case "$_rf_ft_line" in
+        " "*) continue ;;
+        *" $_rf_ft_target") ;;
+        *) continue ;;
+      esac
+      _rf_ft_key="${_rf_ft_line%% *}"
+      _rf_ft_val="${_rf_ft_line#* }"
+      if [ "$_rf_ft_val" = "$_rf_ft_target" ]; then
+        _rf_ft_out="$_rf_ft_key"
+        return 0
+      fi
+    done < "$_rf_ft_file"
+  fi
+  return 1
+}
+
+# Look up a repo mapping entry.
+# Args: $1=source_repo $2=source_repo_prefix $3=target_apparent_name
+#       $4=mapping_file
+# Stores the canonical target repo name in _rf_rm_out and returns 1 if there is
+# no entry. Stored rather than printed so that rlocation does not fork a
+# subshell for it on every lookup.
+# On Windows, matching is case-insensitive.
+#
+# The mapping lists every repository visible from every repository in the
+# binary's runfiles, so it can run to thousands of lines; with awk enabled it
+# is searched by awk like the manifest.
+__runfiles_find_repo_mapping() {
+  _rf_rm_src="$1"
+  _rf_rm_pfx="$2"
+  _rf_rm_tgt="$3"
+  _rf_rm_file="$4"
+  _rf_rm_out=
+
+  if [ -n "${_RULES_SHELL_RUNFILES_AWK:-}" ]; then
+    _rf_rm_out=$(__runfiles_awk '
+      BEGIN { a = ARGV[1]; b = ARGV[2]; c = ARGV[3]; ARGV[1] = ARGV[2] = ARGV[3] = ""
+              if (c) { a = tolower(a); b = tolower(b) } na = length(a); nb = length(b) }
+      { l = c ? tolower($0) : $0
+        if (substr(l, 1, na) == a || substr(l, 1, nb) == b) {
+          r = $0; sub(/^[^,]*,[^,]*,/, "", r); print r; f = 1; exit } }
+      END { exit !f }' "$_rf_rm_file" "${_rf_rm_src},${_rf_rm_tgt}," "${_rf_rm_pfx},${_rf_rm_tgt}," \
+      "$_RLOCATION_CASE_INSENSITIVE") || return 1
+    return 0
+  fi
+
+  if [ -n "$_RLOCATION_CASE_INSENSITIVE" ]; then
+    __runfiles_tolower "${_rf_rm_src},${_rf_rm_tgt},"
+    _rf_rm_pfx_src="$_rf_tl_out"
+    __runfiles_tolower "${_rf_rm_pfx},${_rf_rm_tgt},"
+    _rf_rm_pfx_pfx="$_rf_tl_out"
+    while IFS= read -r _rf_rm_line || [ -n "$_rf_rm_line" ]; do
+      # Compare only the prefix (src,tgt,) case-insensitively — a cheap early
+      # exit for the ~all lines that don't match, without the O(N^2) lowercase
+      # of a whole line.
+      if __runfiles_line_starts_with_ci "$_rf_rm_line" "$_rf_rm_pfx_src" \
+        || __runfiles_line_starts_with_ci "$_rf_rm_line" "$_rf_rm_pfx_pfx"; then
+        _rf_rm_rest="${_rf_rm_line#*,}"
+        _rf_rm_out="${_rf_rm_rest#*,}"
+        return 0
+      fi
+    done < "$_rf_rm_file"
+  else
+    while IFS= read -r _rf_rm_line || [ -n "$_rf_rm_line" ]; do
+      case "$_rf_rm_line" in
+        "${_rf_rm_src},${_rf_rm_tgt},"*|"${_rf_rm_pfx},${_rf_rm_tgt},"*)
+          _rf_rm_rest="${_rf_rm_line#*,}"
+          _rf_rm_out="${_rf_rm_rest#*,}"
+          return 0
+          ;;
+      esac
+    done < "$_rf_rm_file"
+  fi
+  return 1
+}
+
+# Parse the repository name from an exec path, into _rf_pe_out.
+# Scans path segments for /bazel-out/<config>/bin/external/<repo>/ or
+# /bazel-bin/external/<repo>/ and keeps the last matching <repo>; returns 1 if
+# there is none.
+# Equivalent to: grep -E -o '...' | tail -1 | awk -F/ '{print $(NF-1)}'
+__runfiles_parse_exec_path_repo() {
+  _rf_pe_path="$1"
+  _rf_pe_out=""
+  _rf_pe_rest="$_rf_pe_path"
+
+  # Track last 4 path segments via a sliding window.
+  _rf_pe_p4="" _rf_pe_p3="" _rf_pe_p2="" _rf_pe_p1=""
+  while :; do
+    case "$_rf_pe_rest" in
+      */*)
+        _rf_pe_seg="${_rf_pe_rest%%/*}"
+        _rf_pe_rest="${_rf_pe_rest#*/}"
+        ;;
+      *)
+        _rf_pe_seg="$_rf_pe_rest"
+        _rf_pe_rest=""
+        ;;
+    esac
+
+    # Pattern: bazel-bin/external/<repo>
+    if [ "$_rf_pe_p2" = "bazel-bin" ] && [ "$_rf_pe_p1" = "external" ] \
+       && [ -n "$_rf_pe_seg" ]; then
+      _rf_pe_out="$_rf_pe_seg"
+    fi
+    # Pattern: bazel-out/<config>/bin/external/<repo>
+    if [ "$_rf_pe_p4" = "bazel-out" ] && [ "$_rf_pe_p2" = "bin" ] \
+       && [ "$_rf_pe_p1" = "external" ] && [ -n "$_rf_pe_seg" ]; then
+      _rf_pe_out="$_rf_pe_seg"
+    fi
+
+    _rf_pe_p4="$_rf_pe_p3"
+    _rf_pe_p3="$_rf_pe_p2"
+    _rf_pe_p2="$_rf_pe_p1"
+    _rf_pe_p1="$_rf_pe_seg"
+
+    [ -z "$_rf_pe_rest" ] && break
+  done
+
+  [ -n "$_rf_pe_out" ]
+}
+
+# --- Public API ---
+
+# Prints to stdout the runtime location of a data-dependency.
+# The optional second argument specifies the canonical name of the repository
+# whose repository mapping should be used to resolve the repository part of
+# the provided path. If not specified:
+#   * Under bash, the caller's repository is auto-detected via BASH_SOURCE.
+#   * Under a pure POSIX shell there is no BASH_SOURCE, so the main repository
+#     is assumed. Portable callers should pass the source repo explicitly.
+rlocation() {
+  __runfiles_debug "INFO[runfiles.sh]: rlocation($1): start"
+  if __runfiles_is_abs "$1"; then
+    __runfiles_debug "INFO[runfiles.sh]: rlocation($1): absolute path, return"
+    printf '%s\n' "$1"
+    return 0
+  fi
+  case "$1" in
+    ../*|*/..|./*|*/./*|*/.|*//*) # shellcheck disable=SC2254
+      __runfiles_debug "ERROR[runfiles.sh]: rlocation($1): path is not normalized"
+      return 1
+      ;;
+    \\*)
+      __runfiles_debug "ERROR[runfiles.sh]: rlocation($1): absolute path without" \
+        "drive name"
+      return 1
+      ;;
+  esac
+
+  if [ -f "${RUNFILES_REPO_MAPPING:-}" ]; then
+    _rf_rl_target_apparent="${1%%/*}"
+    _rf_rl_remainder=
+    case "$1" in
+      */*) _rf_rl_remainder="${1#*/}" ;;
+    esac
+    if [ -n "$_rf_rl_remainder" ]; then
+      _rf_rl_source_repo=
+      if [ -n "${2+x}" ]; then
+        _rf_rl_source_repo="$2"
+      elif [ -n "${BASH_VERSION:-}" ]; then
+        # Idx 1 is rlocation's caller. The status is ignored: a script outside
+        # the runfiles tree still yields the repository parsed from its exec
+        # path, and one that cannot be resolved at all yields the main one.
+        __runfiles_current_repository 1 || true
+        _rf_rl_source_repo="$_rf_cr_out"
+      fi
+      __runfiles_debug "INFO[runfiles.sh]: rlocation($1): looking up canonical name for ($_rf_rl_target_apparent) from ($_rf_rl_source_repo) in ($RUNFILES_REPO_MAPPING)"
+      __runfiles_compute_repo_prefix "$_rf_rl_source_repo"
+      _rf_rl_source_prefix="$_rf_cp_out"
+      __runfiles_debug "INFO[runfiles.sh]: rlocation($1): matching source_repo ($_rf_rl_source_repo) or prefix ($_rf_rl_source_prefix) with target ($_rf_rl_target_apparent)"
+      __runfiles_find_repo_mapping "$_rf_rl_source_repo" "$_rf_rl_source_prefix" "$_rf_rl_target_apparent" "$RUNFILES_REPO_MAPPING" || true
+      _rf_rl_target_repo="$_rf_rm_out"
+      __runfiles_debug "INFO[runfiles.sh]: rlocation($1): canonical name of target repo is ($_rf_rl_target_repo)"
+      if [ -n "$_rf_rl_target_repo" ]; then
+        _rf_rl_path="$_rf_rl_target_repo/$_rf_rl_remainder"
+      else
+        _rf_rl_path="$1"
+      fi
+    else
+      _rf_rl_path="$1"
+    fi
+  else
+    __runfiles_debug "INFO[runfiles.sh]: rlocation($1): not using repository mapping (${RUNFILES_REPO_MAPPING:-}) since it does not exist"
+    _rf_rl_path="$1"
+  fi
+
+  runfiles_rlocation_checked "$_rf_rl_path"
+}
+
+# Exports the environment variables that subprocesses need in order to use
+# runfiles.
+# If a subprocess is a Bazel-built binary rule that also uses the runfiles
+# libraries under @bazel_tools//tools/<lang>/runfiles, then that binary needs
+# these envvars in order to initialize its own runfiles library.
+runfiles_export_envvars() {
+  if ! [ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ] \
+     && ! [ -d "${RUNFILES_DIR:-/dev/null}" ]; then
+    return 1
+  fi
+
+  if ! [ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]; then
+    if [ -f "$RUNFILES_DIR/MANIFEST" ]; then
+      export RUNFILES_MANIFEST_FILE="$RUNFILES_DIR/MANIFEST"
+    elif [ -f "${RUNFILES_DIR}_manifest" ]; then
+      export RUNFILES_MANIFEST_FILE="${RUNFILES_DIR}_manifest"
+    else
+      export RUNFILES_MANIFEST_FILE=
+    fi
+  elif ! [ -d "${RUNFILES_DIR:-/dev/null}" ]; then
+    case "$RUNFILES_MANIFEST_FILE" in
+      */MANIFEST)
+        if [ -d "${RUNFILES_MANIFEST_FILE%/MANIFEST}" ]; then
+          export RUNFILES_DIR="${RUNFILES_MANIFEST_FILE%/MANIFEST}"
+          export JAVA_RUNFILES="$RUNFILES_DIR"
+        else
+          export RUNFILES_DIR=
+        fi
+        ;;
+      *_manifest)
+        if [ -d "${RUNFILES_MANIFEST_FILE%_manifest}" ]; then
+          export RUNFILES_DIR="${RUNFILES_MANIFEST_FILE%_manifest}"
+          export JAVA_RUNFILES="$RUNFILES_DIR"
+        else
+          export RUNFILES_DIR=
+        fi
+        ;;
+      *)
+        export RUNFILES_DIR=
+        ;;
+    esac
+  fi
+
+}
+
+# The repository of a script that is not in the runfiles tree (the sh_binary
+# entrypoint, or a binary run directly from bazel-bin), parsed from its path
+# under the execroot, into _rf_cr_out: empty for the main repository. $1 is the
+# normalized path, $2 the argument runfiles_current_repository was called
+# with, for the diagnostic.
+__runfiles_exec_path_repository() {
+  __runfiles_parse_exec_path_repo "$1" || true
+  _rf_cr_out="$_rf_pe_out"
+  _rf_cr_have=1
+  if [ -n "$_rf_cr_out" ]; then
+    __runfiles_debug "INFO[runfiles.sh]: runfiles_current_repository($2): ($1) lies in repository ($_rf_cr_out) (parsed exec path)"
+  else
+    __runfiles_debug "INFO[runfiles.sh]: runfiles_current_repository($2): ($1) lies in the main repository (parsed exec path)"
+  fi
+}
+
+# Prints the canonical name of the Bazel repository containing the calling
+# script.
+#
+# Calling convention:
+#   * Under bash, the optional first argument is a numeric index N (default
+#     1) selecting the N-th caller via BASH_SOURCE, so bash consumers can call
+#     runfiles_current_repository with no arguments.
+#   * Under a POSIX shell there is no BASH_SOURCE, so the caller must supply
+#     its own script path as the first argument:
+#
+#       runfiles_current_repository "$0"
+#
+# Note: This function only works correctly with Bzlmod enabled. Without
+# Bzlmod, its return value is ignored if passed to rlocation.
+runfiles_current_repository() {
+  if __runfiles_current_repository "$@"; then
+    _rf_cr_status=0
+  else
+    _rf_cr_status=$?
+  fi
+  if [ -n "$_rf_cr_have" ]; then
+    printf '%s\n' "$_rf_cr_out"
+  fi
+  return $_rf_cr_status
+}
+
+# The lookup behind runfiles_current_repository, with the same arguments and
+# return status, into _rf_cr_out; _rf_cr_have is non-empty when there is a
+# result, which there is not when no caller could be resolved. Stored rather
+# than printed so that rlocation, which needs the caller's repository on every
+# lookup under bash, does not fork for it. A numeric index counts callers from
+# the function that called this one, so the wrapper passes it through as is.
+__runfiles_current_repository() {
+  _rf_cr_out=
+  _rf_cr_have=
+  _rf_cr_raw=
+  _rf_arg="${1:-}"
+  # Non-numeric arg: caller passed a script path (POSIX calling convention).
+  # Accepted under both bash and POSIX so portable scripts work.
+  case "$_rf_arg" in
+    *[!0123456789]*) _rf_cr_raw="$_rf_arg" ;;
+  esac
+  if [ -z "$_rf_cr_raw" ]; then
+    if [ -n "${BASH_VERSION:-}" ]; then
+      # Empty arg defaults to idx=1 (bash convention, N-th caller); BASH_SOURCE
+      # counts from this function, one frame deeper, hence the + 1.
+      # BASH_SOURCE array indexing is bash-only syntax; hide it from POSIX
+      # shells via eval so parsing succeeds. `:-` guards against out-of-bounds
+      # indices under `set -u`.
+      eval '_rf_cr_raw="${BASH_SOURCE[$((${_rf_arg:-1} + 1))]:-}"'
+      if [ -z "$_rf_cr_raw" ]; then
+        __runfiles_debug "ERROR[runfiles.sh]: runfiles_current_repository: no caller" \
+          "path resolvable from BASH_SOURCE (idx=${_rf_arg:-1} out of range)"
+        return 1
+      fi
+    else
+      if [ -z "$_rf_arg" ]; then
+        __runfiles_debug "ERROR[runfiles.sh]: runfiles_current_repository: caller" \
+          "path argument is required under a POSIX shell (pass \"\$0\")"
+      else
+        __runfiles_debug "ERROR[runfiles.sh]: runfiles_current_repository: numeric" \
+          "caller index ($_rf_arg) requires bash; pass the caller" \
+          "path (\"\$0\") instead"
+      fi
+      return 1
+    fi
+  fi
+  if __runfiles_is_abs "$_rf_cr_raw"; then
+    _rf_cr_caller="$_rf_cr_raw"
+  else
+    # dirname/basename without external binaries
+    case "$_rf_cr_raw" in
+      */*) _rf_dir="${_rf_cr_raw%/*}"; [ -z "$_rf_dir" ] && _rf_dir="/" ;;
+      *)   _rf_dir="." ;;
+    esac
+    _rf_base="${_rf_cr_raw##*/}"
+    _rf_cr_caller="$(cd "$_rf_dir" || return 1; pwd)/$_rf_base"
+  fi
+  __runfiles_debug "INFO[runfiles.sh]: runfiles_current_repository(${1:-}): caller's path is ($_rf_cr_caller)"
+
+  _rf_cr_path=
+
+  # If the runfiles manifest exists, search for an entry with target the
+  # caller's path.
+  if [ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]; then
+    __runfiles_normalize_backslashes "$_rf_cr_caller"
+    _rf_cr_norm="$_rf_nb_out"
+    _rf_cr_escaped="$_rf_cr_norm"
+    __runfiles_find_by_target "$_rf_cr_escaped" "$RUNFILES_MANIFEST_FILE" || true
+    _rf_cr_path="$_rf_ft_out"
+    if [ -z "$_rf_cr_path" ]; then
+      __runfiles_debug "ERROR[runfiles.sh]: runfiles_current_repository(${1:-}): ($_rf_cr_norm) is not the target of an entry in the runfiles manifest ($RUNFILES_MANIFEST_FILE)"
+      __runfiles_exec_path_repository "$_rf_cr_norm" "${1:-}"
+      return 1
+    else
+      __runfiles_debug "INFO[runfiles.sh]: runfiles_current_repository(${1:-}): ($_rf_cr_norm) is the target of ($_rf_cr_path) in the runfiles manifest"
+    fi
+  fi
+
+  # If the runfiles directory exists, check if the caller's path is of the
+  # form $RUNFILES_DIR/rlocation_path and if so, set $_rf_cr_path.
+  if [ -z "$_rf_cr_path" ] && [ -d "${RUNFILES_DIR:-/dev/null}" ]; then
+    __runfiles_normalize_backslashes "$_rf_cr_caller"
+    _rf_cr_norm="$_rf_nb_out"
+    _rf_rd="${RUNFILES_DIR%/}"
+    _rf_rd="${_rf_rd%\\}"
+    __runfiles_normalize_backslashes "$_rf_rd"
+    _rf_cr_norm_dir="$_rf_nb_out"
+    if [ -n "$_RLOCATION_CASE_INSENSITIVE" ]; then
+      __runfiles_tolower "$_rf_cr_norm"
+      _rf_cr_norm="$_rf_tl_out"
+      __runfiles_tolower "$_rf_cr_norm_dir"
+      _rf_cr_norm_dir="$_rf_tl_out"
+    fi
+    case "$_rf_cr_norm" in
+      "$_rf_cr_norm_dir"/*)
+        _rf_cr_path="${_rf_cr_norm#"$_rf_cr_norm_dir"}"
+        _rf_cr_path="${_rf_cr_path#/}"
+        ;;
+    esac
+    if [ -z "$_rf_cr_path" ]; then
+      __runfiles_debug "INFO[runfiles.sh]: runfiles_current_repository(${1:-}): ($_rf_cr_norm) does not lie under the runfiles directory ($_rf_cr_norm_dir)"
+      __runfiles_exec_path_repository "$_rf_cr_norm" "${1:-}"
+      return 0
+    else
+      __runfiles_debug "INFO[runfiles.sh]: runfiles_current_repository(${1:-}): ($_rf_cr_caller) has path ($_rf_cr_path) relative to the runfiles directory ($RUNFILES_DIR)"
+    fi
+  fi
+
+  if [ -z "$_rf_cr_path" ]; then
+    __runfiles_debug "ERROR[runfiles.sh]: runfiles_current_repository(${1:-}): cannot determine repository for ($_rf_cr_caller) since neither the runfiles directory (${RUNFILES_DIR:-}) nor the runfiles manifest (${RUNFILES_MANIFEST_FILE:-}) exist"
+    return 1
+  fi
+
+  __runfiles_debug "INFO[runfiles.sh]: runfiles_current_repository(${1:-}): ($_rf_cr_caller) corresponds to rlocation path ($_rf_cr_path)"
+  # Normalize the rlocation path to be of the form repo/pkg/file.
+  _rf_cr_path="${_rf_cr_path#_main/external/}"
+  _rf_cr_path="${_rf_cr_path#_main/../}"
+  _rf_cr_repo="${_rf_cr_path%%/*}"
+  _rf_cr_have=1
+  if [ "$_rf_cr_repo" = "_main" ]; then
+    __runfiles_debug "INFO[runfiles.sh]: runfiles_current_repository(${1:-}): ($_rf_cr_path) lies in the main repository"
+    _rf_cr_out=
+  else
+    __runfiles_debug "INFO[runfiles.sh]: runfiles_current_repository(${1:-}): ($_rf_cr_path) lies in repository ($_rf_cr_repo)"
+    _rf_cr_out="$_rf_cr_repo"
+  fi
+}
+
+# Lexically resolve the "." and ".." segments of the rlocation path $1, into
+# _rf_np_out. Returns 1 for an empty path or one that would escape the runfiles
+# root.
+__runfiles_normalize_rlocation_path() {
+  _rf_np_rest="$1"
+  _rf_np_out=
+  while [ -n "$_rf_np_rest" ]; do
+    case "$_rf_np_rest" in
+      */*) _rf_np_seg="${_rf_np_rest%%/*}"; _rf_np_rest="${_rf_np_rest#*/}" ;;
+      *) _rf_np_seg="$_rf_np_rest"; _rf_np_rest= ;;
+    esac
+    case "$_rf_np_seg" in
+      ""|.) ;;
+      ..)
+        case "$_rf_np_out" in
+          */*) _rf_np_out="${_rf_np_out%/*}" ;;
+          ?*) _rf_np_out= ;;
+          *) return 1 ;;
+        esac
+        ;;
+      *) _rf_np_out="${_rf_np_out:+$_rf_np_out/}$_rf_np_seg" ;;
+    esac
+  done
+  [ -n "$_rf_np_out" ]
+}
+
+# Resolve the target $2 of the manifest entry $1, with $3 appended, to a path in
+# the file system, and print it, or an empty line if there is no such file.
+# $4 is the current lookup depth.
+#
+# Bazel copies the target of an unresolved symlink (ctx.actions.declare_symlink)
+# into the manifest verbatim, so unlike every other target it may be relative.
+# In a materialized runfiles directory the entry is a symlink with that very
+# target, which the file system resolves against the directory containing the
+# symlink. A relative target is therefore an rlocation path relative to the
+# entry's directory, and is looked up in the manifest again.
+__runfiles_resolve_manifest_target() {
+  case "$2" in
+    /*) _rf_rt_abs=1 ;;
+    *) if __runfiles_is_abs "$2"; then _rf_rt_abs=1; else _rf_rt_abs=; fi ;;
+  esac
+  if [ -n "$_rf_rt_abs" ]; then
+    _rf_rt_resolved="$2$3"
+    if [ -e "$_rf_rt_resolved" ]; then
+      __runfiles_debug "INFO[runfiles.sh]: rlocation($1$3): found in manifest as ($_rf_rt_resolved)"
+      printf '%s\n' "$_rf_rt_resolved"
+    else
+      __runfiles_debug "INFO[runfiles.sh]: rlocation($1$3): found in manifest as ($_rf_rt_resolved), but file does not exist"
+      printf '%s\n' ""
+    fi
+    return 0
+  fi
+
+  _rf_rt_dir="${1%/*}"
+  [ "$_rf_rt_dir" = "$1" ] && _rf_rt_dir=
+  if ! __runfiles_normalize_rlocation_path "${_rf_rt_dir:+$_rf_rt_dir/}$2$3"; then
+    __runfiles_debug "ERROR[runfiles.sh]: rlocation($1$3): unresolved symlink target ($2) points outside the runfiles tree"
+    printf '%s\n' ""
+    return 0
+  fi
+  __runfiles_debug "INFO[runfiles.sh]: rlocation($1$3): unresolved symlink target ($2) resolves to ($_rf_np_out)"
+  runfiles_rlocation_checked "$_rf_np_out" "$(($4 + 1))"
+}
+
+runfiles_rlocation_checked() {
+  # FIXME: If the runfiles lookup fails, the exit code of this function is 0
+  #  if and only if the runfiles manifest exists. In particular, the exit code
+  #  behavior is not consistent across platforms.
+  # The optional second argument is the current lookup depth, which only
+  # differs from zero while following the target of an unresolved symlink.
+  _rf_rc_depth="${2:-0}"
+  if [ "$_rf_rc_depth" -gt 32 ]; then
+    __runfiles_debug "ERROR[runfiles.sh]: rlocation($1): too many levels of symbolic links"
+    printf '%s\n' ""
+    return 0
+  fi
+  # The manifest takes precedence over the runfiles directory: whether the
+  # directory is populated is a property of the execution of the action or
+  # test, which is not known at analysis time, so the directory may exist but
+  # contain stale contents from a previous execution. If the manifest exists,
+  # it is always authoritative.
+  if [ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]; then
+    __runfiles_debug "INFO[runfiles.sh]: rlocation($1): looking in RUNFILES_MANIFEST_FILE ($RUNFILES_MANIFEST_FILE)"
+    # If the rlocation path contains a space or newline, it is stored in the
+    # manifest prefixed with a space and with spaces, newlines and backslashes
+    # escaped as \s, \n and \b.
+    _rf_rc_key=; _rf_rc_escaped=; _rf_rc_suffix=
+    case "$1" in
+      *" "*|*"$_RULES_SHELL_RUNFILES_NL"*)
+        # Backslashes first, so that the ones the other two escapes introduce
+        # are left alone.
+        __runfiles_gsub "$1" '\' '\b'
+        __runfiles_gsub "$_rf_gs_out" ' ' '\s'
+        __runfiles_gsub "$_rf_gs_out" "$_RULES_SHELL_RUNFILES_NL" '\n'
+        _rf_rc_key="$_rf_gs_out"
+        _rf_rc_escaped=1
+        __runfiles_debug "INFO[runfiles.sh]: rlocation($1): using escaped search key ($_rf_rc_key)"
+        ;;
+      *)
+        _rf_rc_key="$1"
+        _rf_rc_escaped=
+        ;;
+    esac
+
+    # Look for $1 itself first: the overwhelmingly common case, served by awk
+    # or by a scan that rejects a line with a single `case`.
+    #
+    # An entry with an empty value counts as absent, hence the test on
+    # _rf_fl_val rather than on the exit status.
+    _rf_rc_result=
+    if __runfiles_find_line "${_rf_rc_escaped:+ }$_rf_rc_key" "$RUNFILES_MANIFEST_FILE" &&
+      [ -n "$_rf_fl_val" ]; then
+      _rf_rc_result="$_rf_fl_val"
+      _rf_rc_suffix=
+    elif [ "${1%/*}" != "$1" ] &&
+      __runfiles_find_prefix "$1" "$RUNFILES_MANIFEST_FILE" "$_rf_rc_key" "$_rf_rc_escaped"; then
+      # $1 is not listed, but it may lie under a directory that is. One extra
+      # scan resolves every path prefix at once; a path without a separator
+      # skips the walk entirely, as the _repo_mapping lookup does.
+      _rf_rc_result="$_rf_fp_val"
+      _rf_rc_escaped="$_rf_fp_esc"
+      _rf_rc_suffix="$_rf_fp_suffix"
+    else
+      __runfiles_debug "INFO[runfiles.sh]: rlocation($1): not found in manifest"
+      printf '%s\n' ""
+      return 0
+    fi
+    if [ -n "$_rf_rc_escaped" ]; then
+      __runfiles_gsub "$_rf_rc_result" '\n' "$_RULES_SHELL_RUNFILES_NL"
+      __runfiles_gsub "$_rf_gs_out" '\b' '\'
+      _rf_rc_result="$_rf_gs_out"
+    fi
+    # When a hit that came from a path prefix does not resolve, there is
+    # deliberately no retry with a shorter one, for two reasons:
+    # 1. Manifests generated by Bazel never contain a path that is a prefix
+    #    of another path.
+    # 2. Runfiles libraries for other languages do not check for file
+    #    existence and would have returned the non-existent path. It seems
+    #    better to return no path rather than a potentially different,
+    #    non-empty path.
+    __runfiles_resolve_manifest_target "${1%"$_rf_rc_suffix"}" "$_rf_rc_result" "$_rf_rc_suffix" "$_rf_rc_depth"
+  elif [ -e "${RUNFILES_DIR:-/dev/null}/$1" ]; then
+    __runfiles_debug "INFO[runfiles.sh]: rlocation($1): found under RUNFILES_DIR ($RUNFILES_DIR), return"
+    printf '%s\n' "${RUNFILES_DIR}/$1"
+  else
+    __runfiles_debug "ERROR[runfiles.sh]: cannot look up runfile \"$1\" " \
+      "(RUNFILES_DIR=\"${RUNFILES_DIR:-}\"," \
+      "RUNFILES_MANIFEST_FILE=\"${RUNFILES_MANIFEST_FILE:-}\")"
+    return 1
+  fi
+}
+
+# When running under bash, export functions so they survive exec (used by the
+# launcher). POSIX sh has no equivalent of `export -f`, so this block is
+# skipped in pure POSIX shells.
+if [ -n "${BASH_VERSION:-}" ]; then
+  for _rf_fn in \
+    __runfiles_debug \
+    __runfiles_detect_platform \
+    __runfiles_is_abs \
+    __runfiles_tolower \
+    __runfiles_line_starts_with_ci \
+    __runfiles_normalize_backslashes \
+    __runfiles_gsub \
+    __runfiles_awk \
+    __runfiles_compute_repo_prefix \
+    __runfiles_find_line \
+    __runfiles_find_line_awk \
+    __runfiles_find_line_scan \
+    __runfiles_find_prefix \
+    __runfiles_find_prefix_awk \
+    __runfiles_find_prefix_scan \
+    __runfiles_find_by_target \
+    __runfiles_find_repo_mapping \
+    __runfiles_parse_exec_path_repo \
+    __runfiles_exec_path_repository \
+    __runfiles_current_repository \
+    __runfiles_normalize_rlocation_path \
+    __runfiles_resolve_manifest_target \
+    rlocation \
+    runfiles_export_envvars \
+    runfiles_current_repository \
+    runfiles_rlocation_checked; do
+    # shellcheck disable=SC3045,SC2163  # export -f is the point; the name is variable
+    export -f "$_rf_fn"
+  done
+  unset _rf_fn
+fi
+
+# The repo mapping manifest may not exist with old versions of Bazel.
+RUNFILES_REPO_MAPPING=$(runfiles_rlocation_checked _repo_mapping || echo "")
+export RUNFILES_REPO_MAPPING
diff --git a/tests/bcr/test.sh b/tests/bcr/test.sh
index ce37244..4160dde 100755
--- a/tests/bcr/test.sh
+++ b/tests/bcr/test.sh
@@ -13,17 +13,21 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-# --- begin runfiles.bash initialization v3 ---
-# Copy-pasted from the Bazel Bash runfiles library v3.
-set -uo pipefail; set +e; f=bazel_tools/tools/bash/runfiles/runfiles.bash
+# --- begin runfiles.bash initialization v4 ---
+# Copy-pasted from the Bazel Bash runfiles library v4.
+set -uo pipefail; set +e; f=bazel_tools/tools/bash/runfiles/runfiles.bash; _rf_p=; _rf_a=
+if [ -n "${AWK:-}" ] || [ "${RULES_SHELL_RUNFILES_USE_AWK:-}" != 0 ]; then _rf_a=1; fi
+_rf_d() { [ -f "$1/$f" ] && _rf_p="$1/$f"; }
+_rf_m() { [ -f "$1" ] || return 1; if [ -n "$_rf_a" ]; then \
+  _rf_p=$(${AWK:-awk} -v k="$f " 'index($0,k)==1{print substr($0,length(k)+1);m=1;exit}END{exit !m}' < "$1" 2>/dev/null); case $? in 0) return;; 1) return 1;; esac; fi; \
+  while IFS= read -r _rf_l || [ -n "$_rf_l" ]; do \
+  case "$_rf_l" in "$f "*) _rf_p="${_rf_l#"$f "}"; return;; esac; done < "$1"; return 1; }
+_rf_d "${RUNFILES_DIR:-/dev/null}" || _rf_m "${RUNFILES_MANIFEST_FILE:-/dev/null}" || \
+  _rf_d "$0.runfiles" || _rf_m "$0.runfiles_manifest" || _rf_m "$0.exe.runfiles_manifest" || \
+  { echo>&2 "ERROR: cannot find $f"; exit 1; }
 # shellcheck disable=SC1090
-source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || \
-  source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || \
-  source "$0.runfiles/$f" 2>/dev/null || \
-  source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
-  source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
-  { echo>&2 "ERROR: cannot find $f"; exit 1; }; f=; set -e
-# --- end runfiles.bash initialization v3 ---
+. "$_rf_p" || { echo>&2 "ERROR: cannot source $_rf_p"; exit 1; }; f=; unset -f _rf_d _rf_m; unset _rf_l _rf_p _rf_a; set -e
+# --- end runfiles.bash initialization v4 ---
 
 bin_path="$(rlocation "rules_shell_tests/bin.sh")"
 if [[ ! -x "${bin_path}" ]]; then
diff --git a/tests/runfiles/BUILD b/tests/runfiles/BUILD
index 0e1d4c4..f641c50 100644
--- a/tests/runfiles/BUILD
+++ b/tests/runfiles/BUILD
@@ -1,12 +1,87 @@
 load("@rules_shellcheck//:def.bzl", "shellcheck_test")
+load("//shell:sh_binary.bzl", "sh_binary")
 load("//shell:sh_test.bzl", "sh_test")
 
+# The bash suite against the library as every bash script sees it: through
+# `//shell/runfiles` and the legacy `bazel_tools/tools/bash/runfiles/runfiles.bash`
+# path, where runfiles.bash wraps runfiles.sh with awk enabled.
 sh_test(
-    name = "runfiles_test",
+    name = "runfiles_bash_test",
     srcs = ["runfiles_test.bash"],
     deps = ["//shell/runfiles"],
 )
 
+# The same with awk switched off, so that the shell loops are what the bash
+# suite exercises through the legacy path.
+sh_test(
+    name = "runfiles_bash_no_awk_test",
+    srcs = ["runfiles_test.bash"],
+    env = {"RULES_SHELL_RUNFILES_USE_AWK": "0"},
+    deps = ["//shell/runfiles"],
+)
+
+sh_test(
+    name = "runfiles_sh_from_bash_test",
+    srcs = ["runfiles_test.bash"],
+    # RUNFILES_LIBRARY_FILE is read by runfiles_test.bash's find_runfiles_lib
+    # helper to locate the library under test. Adding the target to `data` so
+    # $(rlocationpath ...) resolves (only `data` is passed to
+    # ctx.expand_location in sh_executable.bzl).
+    data = ["//shell/runfiles:runfiles_sh"],
+    env = {
+        "RUNFILES_LIBRARY_FILE": "$(rlocationpath //shell/runfiles:runfiles_sh)",
+    },
+    deps = ["//shell/runfiles:runfiles_sh"],
+)
+
+sh_test(
+    name = "runfiles_sh_test",
+    srcs = ["runfiles_test.sh"],
+    # Pass the rlocation path of runfiles.sh so the test can find it without
+    # hardcoding the main-repo prefix (which differs between Bzlmod `_main/`
+    # and WORKSPACE `rules_shell/`).
+    data = ["//shell/runfiles:runfiles_sh"],
+    # The suite runs under whatever `#!/bin/sh` resolves to: dash on Debian and
+    # Ubuntu, bash elsewhere. The `test_posix_shell_runfiles` presubmit task
+    # guarantees dash coverage by setting RUNFILES_TEST_REQUIRE_POSIX_SH, and
+    # `runfiles_sh_under_bash_test` covers bash on Linux.
+    env = {
+        "RUNFILES_LIBRARY_FILE": "$(rlocationpath //shell/runfiles:runfiles_sh)",
+    },
+    deps = ["//shell/runfiles:runfiles_sh"],
+)
+
+sh_test(
+    name = "runfiles_sh_no_awk_test",
+    srcs = ["runfiles_test.sh"],
+    data = ["//shell/runfiles:runfiles_sh"],
+    # The same suite with manifests searched by shell loops instead of awk.
+    env = {
+        "RUNFILES_LIBRARY_FILE": "$(rlocationpath //shell/runfiles:runfiles_sh)",
+        "RULES_SHELL_RUNFILES_USE_AWK": "0",
+    },
+    deps = ["//shell/runfiles:runfiles_sh"],
+)
+
+sh_test(
+    name = "runfiles_sh_under_bash_test",
+    srcs = ["runfiles_test_under_bash.sh"],
+    data = [
+        "runfiles_test.sh",
+        "//shell/runfiles:runfiles_sh",
+    ],
+    env = {
+        "RUNFILES_LIBRARY_FILE": "$(rlocationpath //shell/runfiles:runfiles_sh)",
+    },
+    # bash is what the default sh_toolchain resolves to, so this is the
+    # configuration most users run; see runfiles_test_under_bash.sh.
+    target_compatible_with = select({
+        "@platforms//os:linux": [],
+        "//conditions:default": ["@platforms//:incompatible"],
+    }),
+    deps = ["//shell/runfiles:runfiles_sh"],
+)
+
 shellcheck_test(
     name = "runfiles_shellcheck_test",
     data = ["//shell/runfiles:runfiles.bash"],
@@ -19,3 +94,67 @@
         "//conditions:default": [],
     }),
 )
+
+shellcheck_test(
+    name = "runfiles_sh_shellcheck_test",
+    data = ["//shell/runfiles:runfiles.sh"],
+    format = "gcc",
+    severity = "warning",
+    # Fails on Windows with:
+    # '..' is not recognized as an internal or external command, operable program or batch file.
+    target_compatible_with = select({
+        "@platforms//os:windows": ["@platforms//:incompatible"],
+        "//conditions:default": [],
+    }),
+)
+
+# The POSIX suite is linted as sh so that bashisms like `local` do not creep
+# in: dash and bash both accept them, so the suite itself would not notice.
+shellcheck_test(
+    name = "runfiles_test_sh_shellcheck_test",
+    data = ["runfiles_test.sh"],
+    format = "gcc",
+    severity = "warning",
+    target_compatible_with = select({
+        "@platforms//os:windows": ["@platforms//:incompatible"],
+        "//conditions:default": [],
+    }),
+)
+
+shellcheck_test(
+    name = "runfiles_test_under_bash_shellcheck_test",
+    data = ["runfiles_test_under_bash.sh"],
+    format = "gcc",
+    severity = "warning",
+    target_compatible_with = select({
+        "@platforms//os:windows": ["@platforms//:incompatible"],
+        "//conditions:default": [],
+    }),
+)
+
+# Produces the measurement table in shell/runfiles/README.md; see the script
+# for its arguments.
+sh_binary(
+    name = "benchmark",
+    srcs = ["benchmark.sh"],
+    data = [
+        "//shell/runfiles:runfiles.bash",
+        "//shell/runfiles:runfiles.sh",
+    ],
+    env = {
+        "RUNFILES_BASH": "$(rlocationpath //shell/runfiles:runfiles.bash)",
+        "RUNFILES_SH": "$(rlocationpath //shell/runfiles:runfiles.sh)",
+    },
+    tags = ["manual"],
+)
+
+shellcheck_test(
+    name = "benchmark_shellcheck_test",
+    data = ["benchmark.sh"],
+    format = "gcc",
+    severity = "warning",
+    target_compatible_with = select({
+        "@platforms//os:windows": ["@platforms//:incompatible"],
+        "//conditions:default": [],
+    }),
+)
diff --git a/tests/runfiles/benchmark.sh b/tests/runfiles/benchmark.sh
new file mode 100755
index 0000000..791e4f3
--- /dev/null
+++ b/tests/runfiles/benchmark.sh
@@ -0,0 +1,121 @@
+#!/usr/bin/env bash
+# Copyright 2026 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Times the runfiles library against generated manifests and prints the table
+# in shell/runfiles/README.md. Run with
+#
+#   bazel run //tests/runfiles:benchmark -- [--baseline FILE] [--sizes "5000 20000 50000"] [--runs 3]
+#
+# --baseline names a runfiles.bash to time alongside, for example the library
+# before this one: `git show 660e16c:shell/runfiles/runfiles.bash`. The POSIX
+# columns run under `sh`, whatever that is on the host; the last one sets
+# RULES_SHELL_RUNFILES_USE_AWK=0, so that the shell loops search the manifests.
+set -euo pipefail
+
+baseline=
+sizes="5000 20000 50000"
+runs=3
+while [[ $# -gt 0 ]]; do
+  case "$1" in
+    --baseline) baseline="$2"; shift 2 ;;
+    --sizes) sizes="$2"; shift 2 ;;
+    --runs) runs="$2"; shift 2 ;;
+    *) echo >&2 "unknown argument: $1"; exit 2 ;;
+  esac
+done
+
+runfiles_dir="${RUNFILES_DIR:-$0.runfiles}"
+sh_lib="$runfiles_dir/${RUNFILES_SH:?set by the BUILD target}"
+bash_lib="$runfiles_dir/${RUNFILES_BASH:?set by the BUILD target}"
+[[ -f "$sh_lib" && -f "$bash_lib" ]] || { echo >&2 "cannot find the library under $runfiles_dir"; exit 1; }
+
+work=$(mktemp -d)
+trap 'rm -rf "$work"' EXIT
+mkdir -p "$work/dir/_main/pkg"
+: > "$work/leaf"
+: > "$work/repo_mapping"
+ln -s "$work/leaf" "$work/dir/_main/pkg/leaf"
+
+# A manifest of n entries with keys shaped like a pip dependency's, plus
+# _repo_mapping and one main-repository key, which sort to the top.
+generate() {
+  awk -v n="$1" -v leaf="$work/leaf" -v rm="$work/repo_mapping" 'BEGIN {
+    srand(7)
+    np = split("sphinxcontrib_applehelp requests urllib3 charset_normalizer numpy pandas setuptools pip wheel certifi idna packaging typing_extensions pyyaml markupsafe jinja2", p, " ")
+    ns = split("locales/ca/LC_MESSAGES util/ssl_ core/internal _vendor/rich tests/data/fixtures __pycache__ static/css templates/admin", s, " ")
+    for (i = 0; i < n; i++)
+      printf "rules_python++pip+pip_312_%s_py3_none_any_%08x/site-packages/%s/%s/file%d.py %s\n", p[i % np + 1], int(rand() * 4294967296), p[i % np + 1], s[i % ns + 1], i, leaf
+    print "_main/pkg/leaf " leaf
+    print "_repo_mapping " rm
+  }' | LC_ALL=C sort > "$work/m$1"
+}
+
+# Wall time in ms, best of $runs, of: <shell> -c ". <lib>; <body>" with <env>.
+ms() {
+  local shell="$1" lib="$2" extra="$3" body="$4" best=999999 t r
+  for ((r = 0; r < runs; r++)); do
+    t=$( { TIMEFORMAT=%R; time env -u AWK -u RULES_SHELL_RUNFILES_USE_AWK $extra "$shell" -c ". '$lib'; $body" >/dev/null 2>&1; } 2>&1 )
+    t=$(awk -v t="$t" 'BEGIN { printf "%d", t * 1000 }')
+    (( t < best )) && best=$t
+  done
+  echo "$best"
+}
+
+fmt() { if (( $1 >= 1000 )); then awk -v t="$1" 'BEGIN { printf "%.1f s", t / 1000 }'; else echo "$1 ms"; fi; }
+
+# One row: label, env for the manifest or directory, body of lookups.
+row() {
+  local label="$1" env="$2" body="$3" cells=
+  [[ -n "$baseline" ]] && cells+=" $(fmt "$(ms bash "$baseline" "$env" "$body")") |"
+  cells+=" $(fmt "$(ms bash "$bash_lib" "$env" "$body")") |"
+  cells+=" $(fmt "$(ms bash "$sh_lib" "$env" "$body")") |"
+  cells+=" $(fmt "$(ms sh "$sh_lib" "$env" "$body")") |"
+  cells+=" $(fmt "$(ms sh "$sh_lib" "$env RULES_SHELL_RUNFILES_USE_AWK=0" "$body")") |"
+  echo "| $label |$cells"
+}
+
+sh_name=$(sh -c 'echo "${BASH_VERSION:+bash $BASH_VERSION}"'); sh_name="${sh_name:-$(basename "$(readlink -f "$(command -v sh)")")}"
+header="| manifest |"; rule="|---|"
+[[ -n "$baseline" ]] && { header+=" baseline |"; rule+="---|"; }
+header+=" \`runfiles.bash\` | \`runfiles.sh\`, bash | \`runfiles.sh\`, sh | \`runfiles.sh\`, sh, no awk |"; rule+="---|---|---|---|"
+echo "Shells: bash $BASH_VERSION, sh is $sh_name, awk is $(${AWK:-awk} --version 2>/dev/null | head -1 || echo "${AWK:-awk}"). Best of $runs."
+echo
+echo "$header"; echo "$rule"
+
+for n in $sizes; do
+  generate "$n"
+  env="RUNFILES_DIR= RUNFILES_MANIFEST_FILE=$work/m$n"
+  body=
+  for pct in 2 4 6 8 10; do
+    key=$(sed -n "$((n * pct / 10))p" "$work/m$n" | cut -d' ' -f1)
+    body+="x=\$(rlocation $key);"
+  done
+  row "$n lines, 5 keys spread through it" "$env" "$body"
+done
+first=$(echo "$sizes" | cut -d' ' -f1)
+row "$first lines, 1 key near the top" "RUNFILES_DIR= RUNFILES_MANIFEST_FILE=$work/m$first" 'x=$(rlocation _main/pkg/leaf);'
+row "runfiles directory, 1 key" "RUNFILES_DIR=$work/dir RUNFILES_MANIFEST_FILE=" 'x=$(rlocation _main/pkg/leaf);'
+
+last=$(echo "$sizes" | awk '{ print $NF }')
+env="RUNFILES_DIR= RUNFILES_MANIFEST_FILE=$work/m$last"
+body=
+for _ in 1 2 3 4 5 6 7 8 9 10; do
+  for pct in 2 4 6 8 10; do
+    key=$(sed -n "$((last * pct / 10))p" "$work/m$last" | cut -d' ' -f1)
+    body+="x=\$(rlocation $key);"
+  done
+done
+echo
+echo "50 keys spread through the $last-line manifest: $(fmt "$(ms bash "$bash_lib" "$env" "$body")") through \`runfiles.bash\`, $(fmt "$(ms bash "$sh_lib" "$env RULES_SHELL_RUNFILES_USE_AWK=0" "$body")") with the shell loops under bash."
diff --git a/tests/runfiles/runfiles_test.bash b/tests/runfiles/runfiles_test.bash
index fd11d97..c4daf4a 100755
--- a/tests/runfiles/runfiles_test.bash
+++ b/tests/runfiles/runfiles_test.bash
@@ -46,6 +46,8 @@
   ;;
 esac
 
+_RUNFILES_LIBRARY_FILE="${RUNFILES_LIBRARY_FILE:-bazel_tools/tools/bash/runfiles/runfiles.bash}"
+
 function find_runfiles_lib() {
   # Unset existing definitions of the functions we want to test.
   if type rlocation >&/dev/null; then
@@ -58,14 +60,14 @@
       export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
     elif [[ -f "$0.runfiles/MANIFEST" ]]; then
       export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
-    elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
+    elif [[ -f "$0.runfiles/${_RUNFILES_LIBRARY_FILE}" ]]; then
       export RUNFILES_DIR="$0.runfiles"
     fi
   fi
-  if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
-    echo "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash"
+  if [[ -f "${RUNFILES_DIR:-/dev/null}/${_RUNFILES_LIBRARY_FILE}" ]]; then
+    echo "${RUNFILES_DIR}/${_RUNFILES_LIBRARY_FILE}"
   elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
-    grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \
+    grep -m1 "^${_RUNFILES_LIBRARY_FILE} " \
         "$RUNFILES_MANIFEST_FILE" | cut -d ' ' -f 2-
   else
     echo >&2 "ERROR: cannot find //shell/runfiles:runfiles.bash"
@@ -719,6 +721,152 @@
   [[ -z "${RUNFILES_MANIFEST_FILE:-}" ]] || fail
 }
 
+# Through the wrapper, awk is on unless the caller has decided: AWK wins if
+# set, RULES_SHELL_RUNFILES_USE_AWK=0 keeps the shell loops. The wrapper must
+# not touch AWK or leave temporaries behind. Only meaningful when the library
+# under test is reached through the wrapper.
+function test_runfiles_bash_awk_default() {
+  if [[ "$_RUNFILES_LIBRARY_FILE" != *runfiles.bash ]]; then
+    return 0
+  fi
+  export RUNFILES_DIR=mock/runfiles
+  export RUNFILES_MANIFEST_FILE=
+
+  (
+    unset AWK RULES_SHELL_RUNFILES_USE_AWK
+    source "$runfiles_lib_path" || fail
+    if command -v awk >&/dev/null; then
+      [[ "${_RULES_SHELL_RUNFILES_AWK:-}" == awk ]] \
+        || fail "expected awk by default, got '${_RULES_SHELL_RUNFILES_AWK:-}'"
+    else
+      [[ -z "${_RULES_SHELL_RUNFILES_AWK:-}" ]] \
+        || fail "expected the shell loops without awk on PATH"
+    fi
+    [[ -z "${AWK+x}" ]] || fail "the wrapper leaked AWK='${AWK}' into the environment"
+    [[ -z "${_rf_bash_dir+x}" ]] \
+      || fail "the wrapper leaked its temporaries into the environment"
+  ) || fail
+
+  (
+    unset AWK
+    export RULES_SHELL_RUNFILES_USE_AWK=0
+    source "$runfiles_lib_path" || fail
+    [[ -z "${_RULES_SHELL_RUNFILES_AWK:-}" ]] \
+      || fail "expected RULES_SHELL_RUNFILES_USE_AWK=0 to keep the shell loops"
+  ) || fail
+
+  (
+    unset RULES_SHELL_RUNFILES_USE_AWK
+    export AWK="$(command -v awk || echo /no/such/awk)"
+    source "$runfiles_lib_path" || fail
+    [[ "$AWK" == /no/such/awk || "${_RULES_SHELL_RUNFILES_AWK:-}" == "$AWK" ]] \
+      || fail "expected a set AWK to be used as is, got '${_RULES_SHELL_RUNFILES_AWK:-}'"
+    [[ -n "${AWK+x}" ]] || fail "the wrapper must not unset AWK"
+  ) || fail
+}
+
+# The public API stays exported through the wrapper, so that a script which
+# inherited it across exec keeps finding it. Checked from a child bash, which
+# only sees what was exported.
+function test_runfiles_bash_exports_public_api() {
+  if [[ "$_RUNFILES_LIBRARY_FILE" != *runfiles.bash ]]; then
+    return 0
+  fi
+  export RUNFILES_DIR=mock/runfiles
+  export RUNFILES_MANIFEST_FILE=
+  source "$runfiles_lib_path"
+
+  local f
+  for f in rlocation runfiles_export_envvars runfiles_current_repository \
+      runfiles_rlocation_checked; do
+    bash -c "[[ \"\$(type -t $f)\" == function ]]" \
+      || fail "expected $f to be exported as a function"
+  done
+  bash -c '[[ -n "${RUNFILES_REPO_MAPPING+x}" ]]' \
+    || fail "expected RUNFILES_REPO_MAPPING to be exported"
+}
+
+# The v4 snippet, taken from the wrapper's own header, and the wrapper have to
+# work on a host without awk: the snippet's awk attempt fails and its shell
+# loop takes over, and runfiles.sh keeps its shell loops instead of the awk the
+# wrapper asks for.
+function test_runfiles_bash_survives_without_awk() {
+  if [[ "$_RUNFILES_LIBRARY_FILE" != *runfiles.bash ]]; then
+    return 0
+  fi
+  local tmpdir="$(mktemp -d $TEST_TMPDIR/tmp.XXXXXXXX)"
+  local lib_dir="$tmpdir/lib/bazel_tools/tools/bash/runfiles"
+  mkdir -p "$lib_dir"
+  cp "$runfiles_lib_path" "$lib_dir/runfiles.bash"
+  cp "$(dirname "$runfiles_lib_path")/runfiles.sh" "$lib_dir/runfiles.sh"
+  touch "$tmpdir/f"
+  printf 'r/f %s\nbazel_tools/tools/bash/runfiles/runfiles.bash %s\n' "$tmpdir/f" \
+    "$lib_dir/runfiles.bash" > "$tmpdir/manifest"
+  {
+    echo '#!/usr/bin/env bash'
+    sed -n '/^# *# --- begin runfiles.bash initialization v4 ---/,/^# *# --- end runfiles.bash initialization v4 ---/p' \
+      "$runfiles_lib_path" | sed 's/^#       //'
+    echo 'rlocation r/f'
+  } > "$tmpdir/script.sh"
+
+  local actual
+  actual=$(RUNFILES_DIR= RUNFILES_MANIFEST_FILE="$tmpdir/manifest" PATH=/nonexistent "$BASH" "$tmpdir/script.sh")
+  [[ "$actual" == "$tmpdir/f" ]] || fail "expected $tmpdir/f without awk, got: $actual"
+}
+
+# The v4 snippet sources the first library it finds, so a library that fails
+# to load has to abort the script rather than leave it without rlocation. A
+# runfiles directory from before runfiles.sh existed has runfiles.bash and
+# nothing for it to source.
+function test_runfiles_bash_init_aborts_when_library_fails() {
+  if [[ "$_RUNFILES_LIBRARY_FILE" != *runfiles.bash ]]; then
+    return 0
+  fi
+  local tmpdir="$(mktemp -d $TEST_TMPDIR/tmp.XXXXXXXX)"
+  mkdir -p "$tmpdir/stale/bazel_tools/tools/bash/runfiles"
+  cp "$runfiles_lib_path" "$tmpdir/stale/bazel_tools/tools/bash/runfiles/runfiles.bash"
+  touch "$tmpdir/f"
+  printf 'r/f %s\n' "$tmpdir/f" > "$tmpdir/manifest"
+  {
+    echo '#!/usr/bin/env bash'
+    sed -n '/^# *# --- begin runfiles.bash initialization v4 ---/,/^# *# --- end runfiles.bash initialization v4 ---/p' \
+      "$runfiles_lib_path" | sed 's/^#       //'
+    echo 'echo reached'
+  } > "$tmpdir/script.sh"
+
+  local output
+  if output=$(RUNFILES_DIR="$tmpdir/stale" RUNFILES_MANIFEST_FILE="$tmpdir/manifest" "$BASH" "$tmpdir/script.sh" 2>&1); then
+    fail "expected the snippet to abort, got: $output"
+  fi
+  [[ "$output" != *reached* ]] || fail "expected the script not to run past the snippet"
+}
+
+# awk takes an operand of the form name=value as an assignment, so the v4
+# snippet has to reach a manifest with such a path some other way.
+function test_runfiles_bash_manifest_path_with_equals_sign() {
+  if [[ "$_RUNFILES_LIBRARY_FILE" != *runfiles.bash ]]; then
+    return 0
+  fi
+  local tmpdir="$(mktemp -d $TEST_TMPDIR/tmp.XXXXXXXX)"
+  local lib_dir="$tmpdir/lib/bazel_tools/tools/bash/runfiles"
+  mkdir -p "$lib_dir"
+  cp "$runfiles_lib_path" "$lib_dir/runfiles.bash"
+  cp "$(dirname "$runfiles_lib_path")/runfiles.sh" "$lib_dir/runfiles.sh"
+  touch "$tmpdir/f"
+  printf 'r/f %s\nbazel_tools/tools/bash/runfiles/runfiles.bash %s\n' "$tmpdir/f" \
+    "$lib_dir/runfiles.bash" > "$tmpdir/out=1.manifest"
+  {
+    echo '#!/usr/bin/env bash'
+    sed -n '/^# *# --- begin runfiles.bash initialization v4 ---/,/^# *# --- end runfiles.bash initialization v4 ---/p' \
+      "$runfiles_lib_path" | sed 's/^#       //'
+    echo 'rlocation r/f'
+  } > "$tmpdir/script.sh"
+
+  local actual
+  actual=$(RUNFILES_DIR= RUNFILES_MANIFEST_FILE="$tmpdir/out=1.manifest" "$BASH" "$tmpdir/script.sh")
+  [[ "$actual" == "$tmpdir/f" ]] || fail "expected the snippet to find the library through out=1.manifest, got: $actual"
+}
+
 function test_with_grep_env_vars_set() {
   # These influence how grep behaves.
   export GREP_COLOR='1;35;40'
diff --git a/tests/runfiles/runfiles_test.sh b/tests/runfiles/runfiles_test.sh
new file mode 100755
index 0000000..671f39a
--- /dev/null
+++ b/tests/runfiles/runfiles_test.sh
@@ -0,0 +1,1225 @@
+#!/bin/sh
+# shellcheck shell=sh
+# The library under test is sourced from a path computed at run time.
+# shellcheck disable=SC1090
+#
+# Copyright 2018 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# This suite tests the POSIX shell runfiles library, so it is meant to run under
+# a real POSIX shell: bash-in-POSIX-mode still parses bashisms. Which shell
+# `#!/bin/sh` resolves to is the host's choice (dash on Debian and Ubuntu, bash
+# on Fedora and macOS), so the suite runs under whatever it gets, and the
+# `test_posix_shell_runfiles` presubmit task, which runs where /bin/sh is dash,
+# sets RUNFILES_TEST_REQUIRE_POSIX_SH=1 so that interpreter drift there cannot
+# silently cost dash coverage.
+if [ -n "${BASH_VERSION:-}" ] && [ -n "${RUNFILES_TEST_REQUIRE_POSIX_SH:-}" ]; then
+  echo >&2 "ERROR[runfiles_test.sh]: POSIX suite invoked under bash ($BASH_VERSION)" \
+           "with RUNFILES_TEST_REQUIRE_POSIX_SH set"
+  exit 1
+fi
+
+set -eu
+
+NL='
+'
+
+_log_base() {
+  _prefix=$1
+  shift
+  echo >&2 "${_prefix}[runfiles_test.sh ($(date "+%H:%M:%S %z"))] $*"
+}
+
+fail() {
+  _log_base "FAILED" "$@"
+  exit 1
+}
+
+log_fail() {
+  _log_base "FAILED" "$@"
+}
+
+log_info() {
+  _log_base "INFO" "$@"
+}
+
+is_windows() {
+  [ -n "${SYSTEMROOT:-}" ] || [ -n "${COMSPEC:-}" ]
+}
+
+find_runfiles_lib() {
+  if type rlocation >/dev/null 2>&1; then
+    unset -f rlocation
+    unset -f runfiles_export_envvars
+  fi
+
+  # RUNFILES_LIBRARY_FILE is the rlocation path of runfiles.sh, plumbed in via
+  # the sh_test rule's `env` (see tests/runfiles/BUILD). The main-repo prefix
+  # varies between Bzlmod (`_main/...`) and WORKSPACE (`rules_shell/...`), so
+  # we can't hardcode it.
+  _target="${RUNFILES_LIBRARY_FILE:-}"
+  if [ -z "$_target" ]; then
+    echo >&2 "ERROR: RUNFILES_LIBRARY_FILE is not set — the sh_test rule must" \
+             "pass \$(rlocationpath //shell/runfiles:runfiles_sh)"
+    exit 1
+  fi
+
+  if ! [ -d "${RUNFILES_DIR:-/dev/null}" ] && ! [ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]; then
+    if [ -f "$0.runfiles_manifest" ]; then
+      export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
+    elif [ -f "$0.runfiles/MANIFEST" ]; then
+      export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
+    elif [ -f "$0.runfiles/${_target}" ]; then
+      export RUNFILES_DIR="$0.runfiles"
+    fi
+  fi
+  if [ -f "${RUNFILES_DIR:-/dev/null}/${_target}" ]; then
+    echo "${RUNFILES_DIR}/${_target}"
+  elif [ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]; then
+    while IFS= read -r _line; do
+      case "$_line" in
+        "${_target} "*)
+          echo "${_line#"${_target} "}"
+          return 0
+          ;;
+      esac
+    done < "$RUNFILES_MANIFEST_FILE"
+    echo >&2 "ERROR: cannot find $_target"
+    exit 1
+  else
+    echo >&2 "ERROR: cannot find $_target"
+    exit 1
+  fi
+}
+
+test_rlocation_call_requires_no_envvars() {
+  export RUNFILES_DIR=mock/runfiles
+  export RUNFILES_MANIFEST_FILE=
+  export RUNFILES_MANIFEST_ONLY=
+  . "$runfiles_lib_path" || fail
+}
+
+test_rlocation_argument_validation() {
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE=
+  export RUNFILES_MANIFEST_ONLY=
+  . "$runfiles_lib_path"
+
+  if rlocation "../foo" >/dev/null 2>&1; then
+    fail
+  fi
+  if rlocation "foo/.." >/dev/null 2>&1; then
+    fail
+  fi
+  if rlocation "foo/../bar" >/dev/null 2>&1; then
+    fail
+  fi
+  if rlocation "./foo" >/dev/null 2>&1; then
+    fail
+  fi
+  if rlocation "foo/." >/dev/null 2>&1; then
+    fail
+  fi
+  if rlocation "foo/./bar" >/dev/null 2>&1; then
+    fail
+  fi
+  if rlocation "//foo" >/dev/null 2>&1; then
+    fail
+  fi
+  if rlocation "foo//" >/dev/null 2>&1; then
+    fail
+  fi
+  if rlocation "foo//bar" >/dev/null 2>&1; then
+    fail
+  fi
+  if rlocation "\\foo" >/dev/null 2>&1; then
+    fail
+  fi
+}
+
+test_rlocation_abs_path() {
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE=
+  export RUNFILES_MANIFEST_ONLY=
+  . "$runfiles_lib_path"
+
+  if is_windows; then
+    [ "$(rlocation "c:/Foo" || echo failed)" = "c:/Foo" ] || fail
+    [ "$(rlocation "c:\\Foo" || echo failed)" = "c:\\Foo" ] || fail
+  else
+    [ "$(rlocation "/Foo" || echo failed)" = "/Foo" ] || fail
+  fi
+}
+
+test_init_manifest_based_runfiles() {
+  tmpdir="$TEST_TMPDIR/test_init_manifest_based_runfiles"
+  mkdir -p "$tmpdir"
+  cat > "$tmpdir/foo.runfiles_manifest" << EOF
+a/b $tmpdir/c/d
+e/f $tmpdir/g h
+y $tmpdir/y
+c/dir $tmpdir/dir
+unresolved $tmpdir/unresolved
+ h/\si $tmpdir/ j k
+ h/\s\bi $tmpdir/ j k b
+ h/\n\bi $tmpdir/ \bnj k \na
+ dir\swith\sspaces $tmpdir/dir with spaces
+ space\snewline\nbackslash\b_dir $tmpdir/space newline\nbackslash\ba
+EOF
+  mkdir "${tmpdir}/c"
+  mkdir "${tmpdir}/y"
+  mkdir -p "${tmpdir}/dir/deeply/nested"
+  touch "${tmpdir}/c/d" "${tmpdir}/g h"
+  touch "${tmpdir}/dir/file"
+  ln -s /does/not/exist "${tmpdir}/dir/unresolved"
+  touch "${tmpdir}/dir/deeply/nested/file"
+  touch "${tmpdir}/dir/deeply/nested/file with spaces"
+  ln -s /does/not/exist "${tmpdir}/unresolved"
+  touch "${tmpdir}/ j k"
+  touch "${tmpdir}/ j k b"
+  mkdir -p "${tmpdir}/dir with spaces/nested"
+  touch "${tmpdir}/dir with spaces/nested/file"
+  if ! is_windows; then
+    touch "${tmpdir}/ \\nj k ${NL}a"
+    mkdir -p "${tmpdir}/space newline${NL}backslash\\a"
+    touch "${tmpdir}/space newline${NL}backslash\\a/f i\\le"
+  fi
+
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$tmpdir/foo.runfiles_manifest"
+  . "$runfiles_lib_path"
+
+  [ -z "$(rlocation a || echo failed)" ] || fail
+  [ -z "$(rlocation c/d || echo failed)" ] || fail
+  [ "$(rlocation a/b || echo failed)" = "$tmpdir/c/d" ] || fail
+  [ "$(rlocation e/f || echo failed)" = "$tmpdir/g h" ] || fail
+  [ "$(rlocation y || echo failed)" = "$tmpdir/y" ] || fail
+  [ -z "$(rlocation c || echo failed)" ] || fail
+  [ -z "$(rlocation c/di || echo failed)" ] || fail
+  [ "$(rlocation c/dir || echo failed)" = "$tmpdir/dir" ] || fail
+  [ "$(rlocation c/dir/file || echo failed)" = "$tmpdir/dir/file" ] || fail
+  [ -z "$(rlocation c/dir/unresolved || echo failed)" ] || fail
+  [ "$(rlocation c/dir/deeply/nested/file || echo failed)" = "$tmpdir/dir/deeply/nested/file" ] || fail
+  [ "$(rlocation "c/dir/deeply/nested/file with spaces" || echo failed)" = "$tmpdir/dir/deeply/nested/file with spaces" ] || fail
+  [ -z "$(rlocation unresolved || echo failed)" ] || fail
+  [ "$(rlocation "h/ i" || echo failed)" = "$tmpdir/ j k" ] || fail
+  [ "$(rlocation "h/ \\i" || echo failed)" = "$tmpdir/ j k b" ] || fail
+  [ "$(rlocation "dir with spaces" || echo failed)" = "$tmpdir/dir with spaces" ] || fail
+  [ "$(rlocation "dir with spaces/nested/file" || echo failed)" = "$tmpdir/dir with spaces/nested/file" ] || fail
+  if ! is_windows; then
+    [ "$(rlocation "h/${NL}\\i" || echo failed)" = "$tmpdir/ \\nj k ${NL}a" ] || fail
+    [ "$(rlocation "space newline${NL}backslash\\_dir/f i\\le" || echo failed)" = "${tmpdir}/space newline${NL}backslash\\a/f i\\le" ] || fail
+  fi
+
+  rm -r "$tmpdir/c/d" "$tmpdir/g h" "$tmpdir/y" "$tmpdir/dir" "$tmpdir/unresolved" "$tmpdir/ j k" "$tmpdir/dir with spaces"
+  if ! is_windows; then
+    rm -r "$tmpdir/ \\nj k ${NL}a" "${tmpdir}/space newline${NL}backslash\\a"
+    [ -z "$(rlocation "h/${NL}\\i" || echo failed)" ] || fail
+    [ -z "$(rlocation "space newline${NL}backslash\\_dir/f i\\le" || echo failed)" ] || fail
+  fi
+  [ -z "$(rlocation a/b || echo failed)" ] || fail
+  [ -z "$(rlocation e/f || echo failed)" ] || fail
+  [ -z "$(rlocation y || echo failed)" ] || fail
+  [ -z "$(rlocation c/dir || echo failed)" ] || fail
+  [ -z "$(rlocation c/dir/file || echo failed)" ] || fail
+  [ -z "$(rlocation c/dir/deeply/nested/file || echo failed)" ] || fail
+  [ -z "$(rlocation "h/ i" || echo failed)" ] || fail
+  [ -z "$(rlocation "dir with spaces" || echo failed)" ] || fail
+  [ -z "$(rlocation "dir with spaces/nested/file" || echo failed)" ] || fail
+}
+
+test_manifest_based_envvars() {
+  tmpdir="$TEST_TMPDIR/test_manifest_based_envvars"
+  mkdir -p "$tmpdir"
+  echo "a b" > "$tmpdir/foo.runfiles_manifest"
+
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$tmpdir/foo.runfiles_manifest"
+  mkdir -p "$tmpdir/foo.runfiles"
+  . "$runfiles_lib_path"
+
+  runfiles_export_envvars
+  [ "${RUNFILES_DIR:-}" = "$tmpdir/foo.runfiles" ] || fail
+  [ "${RUNFILES_MANIFEST_FILE:-}" = "$tmpdir/foo.runfiles_manifest" ] || fail
+}
+
+test_init_directory_based_runfiles() {
+  tmpdir="$TEST_TMPDIR/test_init_directory_based_runfiles"
+  mkdir -p "$tmpdir"
+
+  export RUNFILES_DIR="${tmpdir}/mock/runfiles"
+  export RUNFILES_MANIFEST_FILE=
+  . "$runfiles_lib_path"
+
+  mkdir -p "$RUNFILES_DIR/a"
+  touch "$RUNFILES_DIR/a/b" "$RUNFILES_DIR/c d"
+  [ "$(rlocation a || echo failed)" = "$RUNFILES_DIR/a" ] || fail
+  [ "$(rlocation c/d || echo failed)" = "failed" ] || fail
+  [ "$(rlocation a/b || echo failed)" = "$RUNFILES_DIR/a/b" ] || fail
+  [ "$(rlocation "c d" || echo failed)" = "$RUNFILES_DIR/c d" ] || fail
+  [ "$(rlocation "c" || echo failed)" = "failed" ] || fail
+  rm -r "$RUNFILES_DIR/a" "$RUNFILES_DIR/c d"
+  [ "$(rlocation a || echo failed)" = "failed" ] || fail
+  [ "$(rlocation a/b || echo failed)" = "failed" ] || fail
+  [ "$(rlocation "c d" || echo failed)" = "failed" ] || fail
+}
+
+# Without RUNFILES_DIR and RUNFILES_MANIFEST_FILE the library derives them from
+# $0. A runfiles directory counts when it holds the library under either of
+# the names //shell/runfiles installs it as, including the legacy bazel_tools
+# one alone, which is all a tree built against Bazel's own runfiles target has.
+test_init_derives_runfiles_dir_from_legacy_location() {
+  tmpdir="$TEST_TMPDIR/test_init_derives_runfiles_dir_from_legacy_location"
+  rm -rf "$tmpdir"
+  mkdir -p "$tmpdir/bin.runfiles/bazel_tools/tools/bash/runfiles" "$tmpdir/bin.runfiles/r"
+  cp "$runfiles_lib_path" "$tmpdir/bin.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash"
+  touch "$tmpdir/bin.runfiles/r/f"
+  printf '#!/bin/sh\n. "%s"\nrlocation r/f\n' "$runfiles_lib_path" > "$tmpdir/bin"
+
+  actual=$(RUNFILES_DIR='' RUNFILES_MANIFEST_FILE='' sh "$tmpdir/bin")
+  [ "$actual" = "$tmpdir/bin.runfiles/r/f" ] \
+    || fail "expected RUNFILES_DIR to be derived from \$0.runfiles, got: $actual"
+}
+
+test_directory_based_runfiles_with_repo_mapping_from_main() {
+  tmpdir="$TEST_TMPDIR/test_directory_based_runfiles_with_repo_mapping_from_main"
+  mkdir -p "$tmpdir"
+
+  export RUNFILES_DIR="${tmpdir}/mock/runfiles"
+  mkdir -p "$RUNFILES_DIR"
+  cat > "$RUNFILES_DIR/_repo_mapping" <<EOF
+,config.json,config.json+1.2.3
+,my_module,_main
+,my_protobuf,protobuf+3.19.2
+,my_workspace,_main
+protobuf+3.19.2,protobuf,protobuf+3.19.2
+protobuf+3.19.2,config.json,config.json+1.2.3
+EOF
+  export RUNFILES_MANIFEST_FILE=
+  . "$runfiles_lib_path"
+
+  mkdir -p "$RUNFILES_DIR/_main/bar"
+  touch "$RUNFILES_DIR/_main/bar/runfile"
+  mkdir -p "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/de eply/nes ted"
+  touch "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/file"
+  touch "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"
+  mkdir -p "$RUNFILES_DIR/protobuf+3.19.2/foo"
+  touch "$RUNFILES_DIR/protobuf+3.19.2/foo/runfile"
+  touch "$RUNFILES_DIR/config.json"
+
+  [ "$(rlocation "my_module/bar/runfile" "" || echo failed)" = "$RUNFILES_DIR/_main/bar/runfile" ] || fail
+  [ "$(rlocation "my_workspace/bar/runfile" "" || echo failed)" = "$RUNFILES_DIR/_main/bar/runfile" ] || fail
+  [ "$(rlocation "my_protobuf/foo/runfile" "" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/foo/runfile" ] || fail
+  [ "$(rlocation "my_protobuf/bar/dir" "" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir" ] || fail
+  [ "$(rlocation "my_protobuf/bar/dir/file" "" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/file" ] || fail
+  [ "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi+le" "" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" ] || fail
+
+  [ "$(rlocation "protobuf/foo/runfile" "" || echo failed)" = "failed" ] || fail
+  [ "$(rlocation "protobuf/bar/dir/dir/de eply/nes ted/fi+le" "" || echo failed)" = "failed" ] || fail
+
+  [ "$(rlocation "_main/bar/runfile" "" || echo failed)" = "$RUNFILES_DIR/_main/bar/runfile" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/foo/runfile" "" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/foo/runfile" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir" "" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir/file" "" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/file" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" "" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" ] || fail
+
+  [ "$(rlocation "config.json" "" || echo failed)" = "$RUNFILES_DIR/config.json" ] || fail
+}
+
+test_directory_based_runfiles_with_repo_mapping_from_other_repo() {
+  tmpdir="$TEST_TMPDIR/test_directory_based_runfiles_with_repo_mapping_from_other_repo"
+  mkdir -p "$tmpdir"
+
+  export RUNFILES_DIR="${tmpdir}/mock/runfiles"
+  mkdir -p "$RUNFILES_DIR"
+  cat > "$RUNFILES_DIR/_repo_mapping" <<EOF
+,config.json,config.json+1.2.3
+,my_module,_main
+,my_protobuf,protobuf+3.19.2
+,my_workspace,_main
+protobuf+3.19.2,protobuf,protobuf+3.19.2
+protobuf+3.19.2,config.json,config.json+1.2.3
+EOF
+  export RUNFILES_MANIFEST_FILE=
+  . "$runfiles_lib_path"
+
+  mkdir -p "$RUNFILES_DIR/_main/bar"
+  touch "$RUNFILES_DIR/_main/bar/runfile"
+  mkdir -p "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/de eply/nes ted"
+  touch "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/file"
+  touch "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"
+  mkdir -p "$RUNFILES_DIR/protobuf+3.19.2/foo"
+  touch "$RUNFILES_DIR/protobuf+3.19.2/foo/runfile"
+  touch "$RUNFILES_DIR/config.json"
+
+  [ "$(rlocation "protobuf/foo/runfile" "protobuf+3.19.2" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/foo/runfile" ] || fail
+  [ "$(rlocation "protobuf/bar/dir" "protobuf+3.19.2" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir" ] || fail
+  [ "$(rlocation "protobuf/bar/dir/file" "protobuf+3.19.2" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/file" ] || fail
+  [ "$(rlocation "protobuf/bar/dir/de eply/nes ted/fi+le" "protobuf+3.19.2" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" ] || fail
+
+  [ "$(rlocation "my_module/bar/runfile" "protobuf+3.19.2" || echo failed)" = "failed" ] || fail
+  [ "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi+le" "protobuf+3.19.2" || echo failed)" = "failed" ] || fail
+
+  [ "$(rlocation "_main/bar/runfile" "protobuf+3.19.2" || echo failed)" = "$RUNFILES_DIR/_main/bar/runfile" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/foo/runfile" "protobuf+3.19.2" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/foo/runfile" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir" "protobuf+3.19.2" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir/file" "protobuf+3.19.2" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/file" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" "protobuf+3.19.2" || echo failed)" = "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" ] || fail
+
+  [ "$(rlocation "config.json" "protobuf+3.19.2" || echo failed)" = "$RUNFILES_DIR/config.json" ] || fail
+}
+
+test_directory_based_runfiles_with_repo_mapping_from_extension_repo() {
+  tmpdir="$TEST_TMPDIR/test_directory_based_runfiles_with_repo_mapping_from_extension_repo"
+  mkdir -p "$tmpdir"
+
+  export RUNFILES_DIR="${tmpdir}/mock/runfiles"
+  mkdir -p "$RUNFILES_DIR"
+  cat > "$RUNFILES_DIR/_repo_mapping" <<EOF
+,config.json,config.json+1.2.3
+,my_module,_main
+,my_protobuf,protobuf+3.19.2
+,my_workspace,_main
+my_module++ex+*,my_module,my_module+
+my_module++ext+*,my_module,my_module+
+my_module++ext+*,repo1,my_module++ext+repo1
+my_module++ext1+*,my_module,my_module+
+EOF
+  export RUNFILES_MANIFEST_FILE=
+  . "$runfiles_lib_path"
+
+  mkdir -p "$RUNFILES_DIR/_main/bar"
+  touch "$RUNFILES_DIR/_main/bar/runfile"
+  mkdir -p "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/de eply/nes ted"
+  touch "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/file"
+  touch "$RUNFILES_DIR/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"
+  mkdir -p "$RUNFILES_DIR/protobuf+3.19.2/foo"
+  touch "$RUNFILES_DIR/protobuf+3.19.2/foo/runfile"
+  touch "$RUNFILES_DIR/config.json"
+  mkdir -p "$RUNFILES_DIR/my_module+/foo"
+  touch "$RUNFILES_DIR/my_module+/foo/runfile"
+  mkdir -p "$RUNFILES_DIR/my_module++ext+repo1/foo"
+  touch "$RUNFILES_DIR/my_module++ext+repo1/foo/runfile"
+  mkdir -p "$RUNFILES_DIR/repo2+/foo"
+  touch "$RUNFILES_DIR/repo2+/foo/runfile"
+
+  [ "$(rlocation "my_module/foo/runfile" "my_module++ext+repo1" || echo failed)" = "$RUNFILES_DIR/my_module+/foo/runfile" ] || fail
+  [ "$(rlocation "repo1/foo/runfile" "my_module++ext+repo1" || echo failed)" = "$RUNFILES_DIR/my_module++ext+repo1/foo/runfile" ] || fail
+  [ "$(rlocation "repo2+/foo/runfile" "my_module++ext+repo1" || echo failed)" = "$RUNFILES_DIR/repo2+/foo/runfile" ] || fail
+}
+
+test_manifest_based_runfiles_with_repo_mapping_from_main() {
+  tmpdir="$TEST_TMPDIR/test_manifest_based_runfiles_with_repo_mapping_from_main"
+  mkdir -p "$tmpdir"
+
+  cat > "$tmpdir/foo.repo_mapping" <<EOF
+,config.json,config.json+1.2.3
+,my_module,_main
+,my_protobuf,protobuf+3.19.2
+,my_workspace,_main
+protobuf+3.19.2,protobuf,protobuf+3.19.2
+protobuf+3.19.2,config.json,config.json+1.2.3
+EOF
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$tmpdir/foo.runfiles_manifest"
+  cat > "$RUNFILES_MANIFEST_FILE" << EOF
+_repo_mapping $tmpdir/foo.repo_mapping
+config.json $tmpdir/config.json
+protobuf+3.19.2/foo/runfile $tmpdir/protobuf+3.19.2/foo/runfile
+_main/bar/runfile $tmpdir/_main/bar/runfile
+protobuf+3.19.2/bar/dir $tmpdir/protobuf+3.19.2/bar/dir
+EOF
+  . "$runfiles_lib_path"
+
+  mkdir -p "$tmpdir/_main/bar"
+  touch "$tmpdir/_main/bar/runfile"
+  mkdir -p "$tmpdir/protobuf+3.19.2/bar/dir/de eply/nes ted"
+  touch "$tmpdir/protobuf+3.19.2/bar/dir/file"
+  touch "$tmpdir/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"
+  mkdir -p "$tmpdir/protobuf+3.19.2/foo"
+  touch "$tmpdir/protobuf+3.19.2/foo/runfile"
+  touch "$tmpdir/config.json"
+
+  [ "$(rlocation "my_module/bar/runfile" "" || echo failed)" = "$tmpdir/_main/bar/runfile" ] || fail
+  [ "$(rlocation "my_workspace/bar/runfile" "" || echo failed)" = "$tmpdir/_main/bar/runfile" ] || fail
+  [ "$(rlocation "my_protobuf/foo/runfile" "" || echo failed)" = "$tmpdir/protobuf+3.19.2/foo/runfile" ] || fail
+  [ "$(rlocation "my_protobuf/bar/dir" "" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir" ] || fail
+  [ "$(rlocation "my_protobuf/bar/dir/file" "" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir/file" ] || fail
+  [ "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi+le" "" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" ] || fail
+
+  [ -z "$(rlocation "protobuf/foo/runfile" "" || echo failed)" ] || fail
+  [ -z "$(rlocation "protobuf/bar/dir/dir/de eply/nes ted/fi+le" "" || echo failed)" ] || fail
+
+  [ "$(rlocation "_main/bar/runfile" "" || echo failed)" = "$tmpdir/_main/bar/runfile" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/foo/runfile" "" || echo failed)" = "$tmpdir/protobuf+3.19.2/foo/runfile" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir" "" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir/file" "" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir/file" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" "" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" ] || fail
+
+  [ "$(rlocation "config.json" "" || echo failed)" = "$tmpdir/config.json" ] || fail
+}
+
+test_manifest_based_runfiles_with_repo_mapping_from_other_repo() {
+  tmpdir="$TEST_TMPDIR/test_manifest_based_runfiles_with_repo_mapping_from_other_repo"
+  mkdir -p "$tmpdir"
+
+  cat > "$tmpdir/foo.repo_mapping" <<EOF
+,config.json,config.json+1.2.3
+,my_module,_main
+,my_protobuf,protobuf+3.19.2
+,my_workspace,_main
+protobuf+3.19.2,protobuf,protobuf+3.19.2
+protobuf+3.19.2,config.json,config.json+1.2.3
+EOF
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$tmpdir/foo.runfiles_manifest"
+  cat > "$RUNFILES_MANIFEST_FILE" << EOF
+_repo_mapping $tmpdir/foo.repo_mapping
+config.json $tmpdir/config.json
+protobuf+3.19.2/foo/runfile $tmpdir/protobuf+3.19.2/foo/runfile
+_main/bar/runfile $tmpdir/_main/bar/runfile
+protobuf+3.19.2/bar/dir $tmpdir/protobuf+3.19.2/bar/dir
+EOF
+  . "$runfiles_lib_path"
+
+  mkdir -p "$tmpdir/_main/bar"
+  touch "$tmpdir/_main/bar/runfile"
+  mkdir -p "$tmpdir/protobuf+3.19.2/bar/dir/de eply/nes ted"
+  touch "$tmpdir/protobuf+3.19.2/bar/dir/file"
+  touch "$tmpdir/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"
+  mkdir -p "$tmpdir/protobuf+3.19.2/foo"
+  touch "$tmpdir/protobuf+3.19.2/foo/runfile"
+  touch "$tmpdir/config.json"
+
+  [ "$(rlocation "protobuf/foo/runfile" "protobuf+3.19.2" || echo failed)" = "$tmpdir/protobuf+3.19.2/foo/runfile" ] || fail
+  [ "$(rlocation "protobuf/bar/dir" "protobuf+3.19.2" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir" ] || fail
+  [ "$(rlocation "protobuf/bar/dir/file" "protobuf+3.19.2" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir/file" ] || fail
+  [ "$(rlocation "protobuf/bar/dir/de eply/nes ted/fi+le" "protobuf+3.19.2" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" ] || fail
+
+  [ -z "$(rlocation "my_module/bar/runfile" "protobuf+3.19.2" || echo failed)" ] || fail
+  [ -z "$(rlocation "my_protobuf/bar/dir/de eply/nes ted/fi+le" "protobuf+3.19.2" || echo failed)" ] || fail
+
+  [ "$(rlocation "_main/bar/runfile" "protobuf+3.19.2" || echo failed)" = "$tmpdir/_main/bar/runfile" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/foo/runfile" "protobuf+3.19.2" || echo failed)" = "$tmpdir/protobuf+3.19.2/foo/runfile" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir" "protobuf+3.19.2" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir/file" "protobuf+3.19.2" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir/file" ] || fail
+  [ "$(rlocation "protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" "protobuf+3.19.2" || echo failed)" = "$tmpdir/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le" ] || fail
+
+  [ "$(rlocation "config.json" "protobuf+3.19.2" || echo failed)" = "$tmpdir/config.json" ] || fail
+}
+
+test_manifest_based_runfiles_with_repo_mapping_from_extension_repo() {
+  tmpdir="$TEST_TMPDIR/test_manifest_based_runfiles_with_repo_mapping_from_extension_repo"
+  mkdir -p "$tmpdir"
+
+  cat > "$tmpdir/foo.repo_mapping" <<EOF
+,config.json,config.json+1.2.3
+,my_module,_main
+,my_protobuf,protobuf+3.19.2
+,my_workspace,_main
+my_module++ex+*,my_module,my_module+
+my_module++ext+*,my_module,my_module+
+my_module++ext+*,repo1,my_module++ext+repo1
+my_module++ext1+*,my_module,my_module+
+EOF
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$tmpdir/foo.runfiles_manifest"
+  cat > "$RUNFILES_MANIFEST_FILE" << EOF
+_repo_mapping $tmpdir/foo.repo_mapping
+config.json $tmpdir/config.json
+protobuf+3.19.2/foo/runfile $tmpdir/protobuf+3.19.2/foo/runfile
+_main/bar/runfile $tmpdir/_main/bar/runfile
+protobuf+3.19.2/bar/dir $tmpdir/protobuf+3.19.2/bar/dir
+my_module+/foo/runfile $tmpdir/my_module+/runfile
+my_module++ext+repo1/foo/runfile $tmpdir/my_module++ext+repo1/runfile
+repo2+/foo/runfile $tmpdir/repo2+/runfile
+EOF
+  . "$runfiles_lib_path"
+
+  mkdir -p "$tmpdir/_main/bar"
+  touch "$tmpdir/_main/bar/runfile"
+  mkdir -p "$tmpdir/protobuf+3.19.2/bar/dir/de eply/nes ted"
+  touch "$tmpdir/protobuf+3.19.2/bar/dir/file"
+  touch "$tmpdir/protobuf+3.19.2/bar/dir/de eply/nes ted/fi+le"
+  mkdir -p "$tmpdir/protobuf+3.19.2/foo"
+  touch "$tmpdir/protobuf+3.19.2/foo/runfile"
+  touch "$tmpdir/config.json"
+  mkdir -p "$tmpdir/my_module+"
+  touch "$tmpdir/my_module+/runfile"
+  mkdir -p "$tmpdir/my_module++ext+repo1"
+  touch "$tmpdir/my_module++ext+repo1/runfile"
+  mkdir -p "$tmpdir/repo2+"
+  touch "$tmpdir/repo2+/runfile"
+
+  [ "$(rlocation "my_module/foo/runfile" "my_module++ext+repo1" || echo failed)" = "$tmpdir/my_module+/runfile" ] || fail
+  [ "$(rlocation "repo1/foo/runfile" "my_module++ext+repo1" || echo failed)" = "$tmpdir/my_module++ext+repo1/runfile" ] || fail
+  [ "$(rlocation "repo2+/foo/runfile" "my_module++ext+repo1" || echo failed)" = "$tmpdir/repo2+/runfile" ] || fail
+}
+
+test_directory_based_runfiles_with_repo_mapping_from_module_root_repo() {
+  # A bzlmod module's canonical name ("rules_shell+") ends in a separator with
+  # no safe characters after it, so the sed pattern that
+  # __runfiles_compute_repo_prefix emulates leaves it unchanged. A wildcard
+  # prefix ("rules_shell+*") would let an unrelated compact-form mapping row
+  # match and rlocation return the wrong file.
+  tmpdir="$TEST_TMPDIR/test_directory_based_runfiles_with_repo_mapping_from_module_root_repo"
+  mkdir -p "$tmpdir"
+
+  export RUNFILES_DIR="${tmpdir}/mock/runfiles"
+  mkdir -p "$RUNFILES_DIR"
+  # No literal "rules_shell+,dep,..." row; only a compact form that matches the
+  # wildcard prefix and nothing else.
+  cat > "$RUNFILES_DIR/_repo_mapping" <<EOF
+rules_shell+*,dep,wrong+
+EOF
+  export RUNFILES_MANIFEST_FILE=
+  . "$runfiles_lib_path"
+
+  mkdir -p "$RUNFILES_DIR/dep/pkg"
+  touch "$RUNFILES_DIR/dep/pkg/f"
+  mkdir -p "$RUNFILES_DIR/wrong+/pkg"
+  touch "$RUNFILES_DIR/wrong+/pkg/f"
+
+  # The compact row does not match, so rlocation keeps the path as given.
+  [ "$(rlocation "dep/pkg/f" "rules_shell+" || echo failed)" = "$RUNFILES_DIR/dep/pkg/f" ] || fail
+}
+
+test_directory_based_envvars() {
+  export RUNFILES_DIR=mock/runfiles
+  export RUNFILES_MANIFEST_FILE=
+  . "$runfiles_lib_path"
+
+  runfiles_export_envvars
+  [ "${RUNFILES_DIR:-}" = "mock/runfiles" ] || fail
+  [ -z "${RUNFILES_MANIFEST_FILE:-}" ] || fail
+}
+
+test_rlocation_auto_detects_source_repo_under_bash() {
+  # Under bash, rlocation with no source-repo arg must walk BASH_SOURCE[2] via
+  # runfiles_current_repository to identify the caller's repo — matching
+  # runfiles.bash. Without this the repo mapping is silently resolved through
+  # the main repo for every downstream sh_binary/sh_test.
+  # Skipped under a POSIX shell (no BASH_SOURCE, no auto-detect possible).
+  if ! command -v bash > /dev/null 2>&1; then
+    return 0
+  fi
+
+  tmpdir="$TEST_TMPDIR/test_rlocation_auto_detects_source_repo_under_bash"
+  mkdir -p "$tmpdir"
+
+  export RUNFILES_DIR="${tmpdir}/mock/runfiles"
+  mkdir -p "$RUNFILES_DIR/some_repo+/pkg"
+
+  # Repo mapping: from source repo "some_repo+", "dep" -> "realdep+".
+  # Also add a main-repo row that maps "dep" somewhere ELSE, so we can tell
+  # whether auto-detection ran (the caller lives in some_repo+, not _main).
+  cat > "$RUNFILES_DIR/_repo_mapping" <<EOF
+,dep,mainrepo_dep+
+some_repo+,dep,realdep+
+EOF
+
+  mkdir -p "$RUNFILES_DIR/realdep+" "$RUNFILES_DIR/mainrepo_dep+"
+  touch "$RUNFILES_DIR/realdep+/foo" "$RUNFILES_DIR/mainrepo_dep+/foo"
+
+  # Helper lives at RUNFILES_DIR/some_repo+/pkg/caller.sh so
+  # runfiles_current_repository can identify its repo as "some_repo+" via the
+  # under-RUNFILES_DIR branch.
+  cat > "$RUNFILES_DIR/some_repo+/pkg/caller.sh" <<HELPER
+#!/bin/bash
+# shellcheck disable=SC1090
+. "$runfiles_lib_path"
+rlocation "dep/foo"
+HELPER
+  chmod +x "$RUNFILES_DIR/some_repo+/pkg/caller.sh"
+
+  export RUNFILES_MANIFEST_FILE=
+
+  actual=$(bash "$RUNFILES_DIR/some_repo+/pkg/caller.sh")
+  [ "$actual" = "$RUNFILES_DIR/realdep+/foo" ] \
+    || fail "expected $RUNFILES_DIR/realdep+/foo, got: $actual"
+}
+
+test_runfiles_current_repository_under_set_u() {
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE=
+  . "$runfiles_lib_path"
+
+  # Enabling nounset must not crash runfiles_current_repository, regardless of
+  # calling convention. rc is expected to be non-zero since no runfiles are
+  # configured, but the function must not error on unbound $1.
+  set -u
+  runfiles_current_repository "$0" >/dev/null 2>&1 || :
+  runfiles_current_repository >/dev/null 2>&1 || :
+  set +u
+}
+
+# runfiles_current_repository resolves the repository of the script at the path
+# it is given, which is the POSIX calling convention: a sourced library has no
+# BASH_SOURCE, so it passes its own location. Writes a library at $1 defining
+# function $2, which reports that repository, or the fixed string $3 for a
+# stale copy that must never be sourced.
+write_current_repository_lib() {
+  mkdir -p "${1%/*}"
+  if [ -n "${3:-}" ]; then
+    printf '%s() {\n  echo "%s"\n}\n' "$2" "$3" > "$1"
+  else
+    printf '%s() {\n  runfiles_current_repository "%s"\n}\n' "$2" "$1" > "$1"
+  fi
+}
+
+test_current_repository_directory_based() {
+  tmpdir="$TEST_TMPDIR/test_current_repository_directory_based"
+  rm -rf "$tmpdir"
+
+  export RUNFILES_DIR="$tmpdir/mock/runfiles"
+  export RUNFILES_MANIFEST_FILE=
+  write_current_repository_lib "$RUNFILES_DIR/protobuf+3.19.2/foo/lib.sh" repo_of_other
+  write_current_repository_lib "$RUNFILES_DIR/_main/bar/lib.sh" repo_of_main
+  . "$runfiles_lib_path"
+
+  . "$(rlocation "protobuf+3.19.2/foo/lib.sh" "")" || fail
+  [ "$(repo_of_other || echo failed)" = "protobuf+3.19.2" ] \
+    || fail "expected protobuf+3.19.2, got: $(repo_of_other || echo failed)"
+
+  . "$(rlocation "_main/bar/lib.sh" "")" || fail
+  [ "$(repo_of_main || echo failed)" = "" ] \
+    || fail "expected the main repository, got: $(repo_of_main || echo failed)"
+}
+
+test_current_repository_manifest_based() {
+  tmpdir="$TEST_TMPDIR/test_current_repository_manifest_based"
+  rm -rf "$tmpdir"
+
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$tmpdir/foo.runfiles_manifest"
+  write_current_repository_lib "$tmpdir/protobuf+3.19.2/foo/lib.sh" repo_of_other
+  write_current_repository_lib "$tmpdir/_main/bar/lib.sh" repo_of_main
+  cat > "$RUNFILES_MANIFEST_FILE" <<EOF
+protobuf+3.19.2/foo/lib.sh $tmpdir/protobuf+3.19.2/foo/lib.sh
+_main/bar/lib.sh $tmpdir/_main/bar/lib.sh
+EOF
+  . "$runfiles_lib_path"
+
+  . "$(rlocation "protobuf+3.19.2/foo/lib.sh" "")" || fail
+  [ "$(repo_of_other || echo failed)" = "protobuf+3.19.2" ] \
+    || fail "expected protobuf+3.19.2, got: $(repo_of_other || echo failed)"
+
+  . "$(rlocation "_main/bar/lib.sh" "")" || fail
+  [ "$(repo_of_main || echo failed)" = "" ] \
+    || fail "expected the main repository, got: $(repo_of_main || echo failed)"
+}
+
+# Both variables are set at once e.g. on Windows with --enable_runfiles, where
+# the runfiles directory holds the MANIFEST that runfiles_export_envvars
+# promotes to RUNFILES_MANIFEST_FILE. The manifest maps rlocation paths to the
+# *original* files, so a caller looked up through it is never found under the
+# directory.
+test_current_repository_directory_and_manifest_based() {
+  tmpdir="$TEST_TMPDIR/test_current_repository_directory_and_manifest_based"
+  rm -rf "$tmpdir"
+
+  export RUNFILES_DIR="$tmpdir/mock/runfiles"
+  export RUNFILES_MANIFEST_FILE="$RUNFILES_DIR/MANIFEST"
+  write_current_repository_lib "$tmpdir/protobuf+3.19.2/foo/lib.sh" repo_of_other
+  write_current_repository_lib "$tmpdir/_main/bar/lib.sh" repo_of_main
+  # The runfiles directory may hold stale contents, so the manifest wins.
+  write_current_repository_lib "$RUNFILES_DIR/protobuf+3.19.2/foo/lib.sh" repo_of_other stale
+  write_current_repository_lib "$RUNFILES_DIR/_main/bar/lib.sh" repo_of_main stale
+  cat > "$RUNFILES_MANIFEST_FILE" <<EOF
+protobuf+3.19.2/foo/lib.sh $tmpdir/protobuf+3.19.2/foo/lib.sh
+_main/bar/lib.sh $tmpdir/_main/bar/lib.sh
+EOF
+  . "$runfiles_lib_path"
+
+  [ "$(rlocation "protobuf+3.19.2/foo/lib.sh" "" || echo failed)" = "$tmpdir/protobuf+3.19.2/foo/lib.sh" ] || fail
+  . "$(rlocation "protobuf+3.19.2/foo/lib.sh" "")" || fail
+  [ "$(repo_of_other || echo failed)" = "protobuf+3.19.2" ] \
+    || fail "expected protobuf+3.19.2, got: $(repo_of_other || echo failed)"
+
+  [ "$(rlocation "_main/bar/lib.sh" "" || echo failed)" = "$tmpdir/_main/bar/lib.sh" ] || fail
+  . "$(rlocation "_main/bar/lib.sh" "")" || fail
+  [ "$(repo_of_main || echo failed)" = "" ] \
+    || fail "expected the main repository, got: $(repo_of_main || echo failed)"
+}
+
+# Platform detection must work without shelling out to uname. Drive
+# __runfiles_detect_platform directly with a faked environment so that the
+# Windows branches are covered on non-Windows hosts too.
+test_platform_detection_without_uname() {
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE=
+  . "$runfiles_lib_path"
+
+  tmpdir="$TEST_TMPDIR/test_platform_detection_without_uname"
+  mkdir -p "$tmpdir"
+
+  # A /proc/version that does not exist, so only the environment is consulted.
+  absent="$tmpdir/absent"
+
+  check_detection() {
+    _what="$1"
+    _want="$2"
+    if [ "${_RLOCATION_ISABS_WINDOWS:-}" != "$_want" ] ||
+      [ "${_RLOCATION_CASE_INSENSITIVE:-}" != "$_want" ]; then
+      fail "$_what: expected windows='$_want', got" \
+        "_RLOCATION_ISABS_WINDOWS='${_RLOCATION_ISABS_WINDOWS:-}'" \
+        "_RLOCATION_CASE_INSENSITIVE='${_RLOCATION_CASE_INSENSITIVE:-}'"
+    fi
+  }
+
+  # 1. MSYSTEM, set by every MSYS2 / MinGW / Git-for-Windows shell.
+  (
+    MSYSTEM=MINGW64 __runfiles_detect_platform "$absent"
+    check_detection "MSYSTEM=MINGW64" 1
+  ) || return 1
+
+  # 2. OSTYPE, set by bash on Cygwin and MSYS.
+  for ostype in cygwin msys win32; do
+    (
+      unset MSYSTEM
+      OSTYPE="$ostype" __runfiles_detect_platform "$absent"
+      check_detection "OSTYPE=$ostype" 1
+    ) || return 1
+  done
+
+  # 3. /proc/version naming a Windows runtime.
+  for procver in "CYGWIN_NT-10.0-19045 version 3.4.7" \
+    "MSYS_NT-10.0-19045 version 3.4.7" \
+    "MINGW64_NT-10.0-19045 version 3.4.7"; do
+    echo "$procver" > "$tmpdir/proc_version"
+    (
+      unset MSYSTEM OSTYPE
+      __runfiles_detect_platform "$tmpdir/proc_version"
+      check_detection "/proc/version=$procver" 1
+    ) || return 1
+  done
+
+  # 4. A Unix /proc/version wins over inherited Windows env vars: WSL can
+  #    import WINDIR from the host through WSLENV and must not be mistaken for
+  #    a Windows shell.
+  echo "Linux version 5.15.0-1051-microsoft-standard-WSL2" > "$tmpdir/proc_version"
+  (
+    unset MSYSTEM OSTYPE
+    WINDIR='C:\Windows' SYSTEMROOT='C:\Windows' \
+      __runfiles_detect_platform "$tmpdir/proc_version"
+    check_detection "WSL with WINDIR set" ""
+  ) || return 1
+
+  # 5. No /proc at all, but Windows env vars present.
+  (
+    unset MSYSTEM OSTYPE
+    WINDIR='C:\Windows' __runfiles_detect_platform "$absent"
+    check_detection "WINDIR without /proc" 1
+  ) || return 1
+
+  # 6. Nothing indicates Windows.
+  (
+    unset MSYSTEM OSTYPE WINDIR SystemRoot SYSTEMROOT
+    __runfiles_detect_platform "$absent"
+    check_detection "no Windows signals" ""
+  ) || return 1
+
+  # The library must leave no temporaries behind in the caller's environment.
+  for leaked in _rf_dp_win _rf_dp_line _rf_dp_procver_file; do
+    eval "_value=\${$leaked:-}"
+    if [ -n "$_value" ]; then
+      fail "detection leaked \$$leaked='$_value' into the environment"
+    fi
+  done
+}
+
+# A manifest lookup falls back to the longest path prefix of the requested
+# path, to resolve files only reachable through a directory runfile. That
+# prefix has to end on a path separator: `c/dir` must not be treated as a
+# prefix of `c/dirx/file` or of `c/dirfile`. The shared bash suite has no such
+# collision, so cover it here.
+test_manifest_prefix_respects_path_boundaries() {
+  tmpdir="$TEST_TMPDIR/test_manifest_prefix_respects_path_boundaries"
+  rm -rf "$tmpdir"
+  mkdir -p "$tmpdir/dir" "$tmpdir/dirx"
+  touch "$tmpdir/dir/file" "$tmpdir/dirx/file" "$tmpdir/dirfile"
+  echo "c/dir $tmpdir/dir" > "$tmpdir/manifest"
+
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$tmpdir/manifest"
+  . "$runfiles_lib_path"
+
+  [ "$(rlocation c/dir/file)" = "$tmpdir/dir/file" ] \
+    || fail "expected c/dir/file to resolve through the c/dir prefix"
+  [ -z "$(rlocation c/dirx/file)" ] \
+    || fail "c/dir must not be treated as a path prefix of c/dirx/file"
+  [ -z "$(rlocation c/dirfile)" ] \
+    || fail "c/dir must not be treated as a path prefix of c/dirfile"
+  # The prefix walk must also stop at the shortest segment, not match a bare
+  # substring of the first one.
+  [ -z "$(rlocation c)" ] || fail "c must not resolve"
+}
+
+# Manifest matching is case-insensitive on Windows. The shared bash suite only
+# covers that when actually running on Windows, so force the flag on here to
+# get the branch exercised everywhere.
+test_manifest_lookup_case_insensitive() {
+  tmpdir="$TEST_TMPDIR/test_manifest_lookup_case_insensitive"
+  rm -rf "$tmpdir"
+  mkdir -p "$tmpdir/dir"
+  touch "$tmpdir/f" "$tmpdir/dir/file"
+  cat > "$tmpdir/manifest" <<EOF
+A/B/File.TXT $tmpdir/f
+C/Dir $tmpdir/dir
+EOF
+
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$tmpdir/manifest"
+  . "$runfiles_lib_path"
+  export _RLOCATION_CASE_INSENSITIVE=1
+
+  [ "$(rlocation a/b/file.txt)" = "$tmpdir/f" ] \
+    || fail "expected a case-insensitive exact match"
+  [ "$(rlocation A/B/File.TXT)" = "$tmpdir/f" ] \
+    || fail "expected the exact-case lookup to keep working"
+  [ "$(rlocation c/dir/file)" = "$tmpdir/dir/file" ] \
+    || fail "expected a case-insensitive prefix match"
+  [ -z "$(rlocation c/dirx/file)" ] \
+    || fail "case-insensitive matching must still respect path boundaries"
+}
+
+# Manifests are searched with awk when it can be found, and with shell loops
+# under RULES_SHELL_RUNFILES_USE_AWK=0, which is how `runfiles_sh_no_awk_test`
+# runs this whole suite. The tests below cover the switch itself: awk is on by
+# default, AWK names the program, and one that cannot be found leaves the shell
+# loops in place rather than breaking every lookup.
+write_awk_test_manifest() {
+  rm -rf "$1"
+  mkdir -p "$1/dir"
+  touch "$1/f" "$1/dir/file"
+  cat > "$1/manifest" <<EOF
+r/f $1/f
+r/d $1/dir
+EOF
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$1/manifest"
+}
+
+test_awk_on_by_default() {
+  if ! command -v awk >/dev/null 2>&1; then
+    log_info "no awk on PATH, skipping"
+    return 0
+  fi
+  tmpdir="$TEST_TMPDIR/test_awk_on_by_default"
+  write_awk_test_manifest "$tmpdir"
+
+  unset AWK RULES_SHELL_RUNFILES_USE_AWK
+  . "$runfiles_lib_path"
+
+  [ "${_RULES_SHELL_RUNFILES_AWK:-}" = awk ] \
+    || fail "expected awk from PATH, got: ${_RULES_SHELL_RUNFILES_AWK:-}"
+  [ "$(rlocation r/f)" = "$tmpdir/f" ] || fail "expected an exact match through awk"
+  [ "$(rlocation r/d/file)" = "$tmpdir/dir/file" ] \
+    || fail "expected a prefix match through awk"
+  [ -z "$(rlocation r/nope)" ] || fail "expected a miss through awk"
+}
+
+test_awk_disabled_by_env() {
+  tmpdir="$TEST_TMPDIR/test_awk_disabled_by_env"
+  write_awk_test_manifest "$tmpdir"
+
+  unset AWK
+  export RULES_SHELL_RUNFILES_USE_AWK=0
+  . "$runfiles_lib_path"
+
+  [ -z "${_RULES_SHELL_RUNFILES_AWK:-}" ] \
+    || fail "expected RULES_SHELL_RUNFILES_USE_AWK=0 to keep the shell loops"
+  [ "$(rlocation r/f)" = "$tmpdir/f" ] || fail "expected an exact match without awk"
+  [ "$(rlocation r/d/file)" = "$tmpdir/dir/file" ] \
+    || fail "expected a prefix match without awk"
+  [ -z "$(rlocation r/nope)" ] || fail "expected a miss without awk"
+}
+
+test_awk_enabled_by_program() {
+  if ! command -v awk >/dev/null 2>&1; then
+    log_info "no awk on PATH, skipping"
+    return 0
+  fi
+  tmpdir="$TEST_TMPDIR/test_awk_enabled_by_program"
+  write_awk_test_manifest "$tmpdir"
+  printf '#!/bin/sh\n: > "%s/called"\nexec awk "$@"\n' "$tmpdir" > "$tmpdir/myawk"
+  chmod +x "$tmpdir/myawk"
+
+  unset RULES_SHELL_RUNFILES_USE_AWK
+  export AWK="$tmpdir/myawk"
+  . "$runfiles_lib_path"
+
+  [ "${_RULES_SHELL_RUNFILES_AWK:-}" = "$tmpdir/myawk" ] \
+    || fail "expected AWK to be selected, got: ${_RULES_SHELL_RUNFILES_AWK:-}"
+  [ "$(rlocation r/f)" = "$tmpdir/f" ] || fail "expected an exact match through awk"
+  [ -e "$tmpdir/called" ] || fail "expected the configured awk program to be run"
+  [ "$(rlocation r/d/file)" = "$tmpdir/dir/file" ] \
+    || fail "expected a prefix match through awk"
+  [ -z "$(rlocation r/nope)" ] || fail "expected a miss through awk"
+}
+
+test_awk_falls_back_when_program_is_missing() {
+  tmpdir="$TEST_TMPDIR/test_awk_falls_back_when_program_is_missing"
+  write_awk_test_manifest "$tmpdir"
+
+  export AWK="$tmpdir/no-such-awk"
+  . "$runfiles_lib_path"
+
+  [ -z "${_RULES_SHELL_RUNFILES_AWK:-}" ] \
+    || fail "expected the shell loops when the awk program is missing"
+  [ "$(rlocation r/f)" = "$tmpdir/f" ] || fail "expected an exact match without awk"
+  [ "$(rlocation r/d/file)" = "$tmpdir/dir/file" ] \
+    || fail "expected a prefix match without awk"
+  [ -z "$(rlocation r/nope)" ] || fail "expected a miss without awk"
+}
+
+# Writes a runfiles layout containing unresolved symlinks with relative
+# targets, both as a manifest pointing at the original files and as a
+# materialized runfiles directory.
+write_relative_symlink_target_layout() {
+  _wl_dir="$1/foo.runfiles"
+
+  mkdir -p "$1/original/dir/deeply/nested"
+  echo file > "$1/original/file"
+  echo nested_file > "$1/original/dir/deeply/nested/file"
+  # Lies next to the runfiles directory and is thus only reachable through a
+  # relative target that leaves the runfiles tree.
+  echo outside > "$1/outside"
+
+  cat > "$1/foo.runfiles_manifest" <<EOF
+_main/pkg/file $1/original/file
+_main/pkg/dir $1/original/dir
+_main/pkg/link ../pkg/file
+_main/pkg/nested/link ../../pkg/link
+_main/pkg/dir_link ./dir
+_main/pkg/dangling ../pkg/missing
+_main/pkg/escaping ../../../outside
+_main/pkg/loop_a loop_b
+_main/pkg/loop_b loop_a
+ _main/pkg/link\swith\sspaces ../pkg/file
+EOF
+
+  mkdir -p "$_wl_dir/_main/pkg/nested"
+  ln -s "$1/original/file" "$_wl_dir/_main/pkg/file"
+  ln -s "$1/original/dir" "$_wl_dir/_main/pkg/dir"
+  ln -s ../pkg/file "$_wl_dir/_main/pkg/link"
+  ln -s ../../pkg/link "$_wl_dir/_main/pkg/nested/link"
+  ln -s ./dir "$_wl_dir/_main/pkg/dir_link"
+  ln -s ../pkg/missing "$_wl_dir/_main/pkg/dangling"
+  ln -s ../../../outside "$_wl_dir/_main/pkg/escaping"
+  ln -s loop_b "$_wl_dir/_main/pkg/loop_a"
+  ln -s loop_a "$_wl_dir/_main/pkg/loop_b"
+  ln -s ../pkg/file "$_wl_dir/_main/pkg/link with spaces"
+}
+
+# Asserts that $1 resolves to a file with contents $2. Only the contents are
+# compared, since the path necessarily differs between the two lookup modes: a
+# materialized runfiles directory resolves to the entry in that directory, not
+# to the file it points at.
+assert_rlocation_contents() {
+  _ac_resolved="$(rlocation "$1" || echo failed)"
+  [ -f "$_ac_resolved" ] || fail "$1 did not resolve to a file, got: $_ac_resolved"
+  [ "$(cat "$_ac_resolved")" = "$2" ] \
+    || fail "$1 resolved to $_ac_resolved with unexpected contents"
+}
+
+# Asserts that $1 does not resolve, which rlocation reports as an empty result
+# when it uses the manifest and as a non-zero exit code when it uses the
+# runfiles directory (see the FIXME on runfiles_rlocation_checked).
+assert_no_rlocation() {
+  _an_resolved="$(rlocation "$1" || echo failed)"
+  [ -z "$_an_resolved" ] || [ "$_an_resolved" = failed ] \
+    || fail "$1 unexpectedly resolved to $_an_resolved"
+}
+
+# The lookups whose outcome must not depend on whether the manifest or the
+# runfiles directory backs them: resolving a relative target against the
+# manifest has to arrive at the same file that the file system arrives at when
+# resolving the corresponding symlink in the runfiles directory.
+assert_relative_symlink_target_lookups() {
+  assert_rlocation_contents _main/pkg/link file
+  assert_rlocation_contents _main/pkg/nested/link file
+  assert_rlocation_contents "_main/pkg/link with spaces" file
+  # A relative target that resolves to a directory runfile also resolves paths
+  # underneath it.
+  [ -d "$(rlocation _main/pkg/dir_link || echo failed)" ] || fail
+  assert_rlocation_contents _main/pkg/dir_link/deeply/nested/file nested_file
+  # A target that doesn't resolve to an existing file behaves like a missing
+  # runfile.
+  assert_no_rlocation _main/pkg/dangling
+  assert_no_rlocation _main/pkg/dir_link/does/not/exist
+  # A cycle terminates instead of looping forever.
+  assert_no_rlocation _main/pkg/loop_a
+}
+
+test_manifest_based_relative_symlink_targets() {
+  tmpdir="$TEST_TMPDIR/test_manifest_based_relative_symlink_targets"
+  rm -rf "$tmpdir"
+  write_relative_symlink_target_layout "$tmpdir"
+
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$tmpdir/foo.runfiles_manifest"
+  . "$runfiles_lib_path"
+
+  assert_relative_symlink_target_lookups
+  # The one lookup the manifest cannot reproduce: a relative target that leaves
+  # the runfiles tree can only be resolved against a materialized runfiles
+  # directory, whose existence the manifest does not imply. Bazel does not
+  # generate such a runfile.
+  assert_no_rlocation _main/pkg/escaping
+}
+
+test_directory_based_relative_symlink_targets() {
+  # MSYS2 may materialize symlinks as copies, which does not preserve relative
+  # targets.
+  if is_windows; then
+    return 0
+  fi
+
+  tmpdir="$TEST_TMPDIR/test_directory_based_relative_symlink_targets"
+  rm -rf "$tmpdir"
+  write_relative_symlink_target_layout "$tmpdir"
+
+  export RUNFILES_DIR="$tmpdir/foo.runfiles"
+  export RUNFILES_MANIFEST_FILE=
+  . "$runfiles_lib_path"
+
+  assert_relative_symlink_target_lookups
+  assert_rlocation_contents _main/pkg/escaping outside
+}
+
+# The documented initialization snippet, taken from the library's own header,
+# and the library have to work on a host without awk: the snippet's awk attempt
+# fails and its shell loop takes over, and the library keeps its shell loops.
+test_survives_without_awk() {
+  tmpdir="$TEST_TMPDIR/test_survives_without_awk"
+  rm -rf "$tmpdir"
+  mkdir -p "$tmpdir/lib/rules_shell/shell/runfiles"
+  cp "$runfiles_lib_path" "$tmpdir/lib/rules_shell/shell/runfiles/runfiles.sh"
+  touch "$tmpdir/f"
+  printf 'r/f %s\nrules_shell/shell/runfiles/runfiles.sh %s\n' "$tmpdir/f" \
+    "$tmpdir/lib/rules_shell/shell/runfiles/runfiles.sh" > "$tmpdir/manifest"
+  {
+    echo '#!/bin/sh'
+    sed -n '/^# *# --- begin runfiles.sh initialization v4 ---/,/^# *# --- end runfiles.sh initialization v4 ---/p' \
+      "$runfiles_lib_path" | sed 's/^#       //'
+    echo 'rlocation r/f'
+  } > "$tmpdir/script.sh"
+  sh_path=$(command -v sh)
+
+  actual=$(RUNFILES_DIR='' RUNFILES_MANIFEST_FILE="$tmpdir/manifest" \
+    PATH=/nonexistent "$sh_path" "$tmpdir/script.sh")
+  [ "$actual" = "$tmpdir/f" ] || fail "expected $tmpdir/f without awk, got: $actual"
+}
+
+# The snippet sources the first library it finds, so a library that fails to
+# load has to abort the script rather than leave it without rlocation.
+test_init_snippet_aborts_when_library_fails() {
+  tmpdir="$TEST_TMPDIR/test_init_snippet_aborts_when_library_fails"
+  rm -rf "$tmpdir"
+  mkdir -p "$tmpdir/broken/rules_shell/shell/runfiles"
+  echo 'return 1' > "$tmpdir/broken/rules_shell/shell/runfiles/runfiles.sh"
+  {
+    echo '#!/bin/sh'
+    sed -n '/^# *# --- begin runfiles.sh initialization v4 ---/,/^# *# --- end runfiles.sh initialization v4 ---/p' \
+      "$runfiles_lib_path" | sed 's/^#       //'
+    echo 'echo reached'
+  } > "$tmpdir/script.sh"
+
+  if output=$(RUNFILES_DIR="$tmpdir/broken" RUNFILES_MANIFEST_FILE='' sh "$tmpdir/script.sh" 2>&1); then
+    fail "expected the snippet to abort, got: $output"
+  fi
+  [ "${output#*reached}" = "$output" ] || fail "expected the script not to run past the snippet"
+}
+
+# awk takes an operand of the form name=value as an assignment, so a manifest
+# path shaped like that has to reach it some other way, in the library and in
+# the snippet alike.
+test_manifest_path_with_equals_sign() {
+  tmpdir="$TEST_TMPDIR/test_manifest_path_with_equals_sign"
+  rm -rf "$tmpdir"
+  mkdir -p "$tmpdir/lib/rules_shell/shell/runfiles"
+  cp "$runfiles_lib_path" "$tmpdir/lib/rules_shell/shell/runfiles/runfiles.sh"
+  touch "$tmpdir/f"
+  printf 'r/f %s\nrules_shell/shell/runfiles/runfiles.sh %s\n' "$tmpdir/f" \
+    "$tmpdir/lib/rules_shell/shell/runfiles/runfiles.sh" > "$tmpdir/out=1.manifest"
+
+  export RUNFILES_DIR=
+  export RUNFILES_MANIFEST_FILE="$tmpdir/out=1.manifest"
+  . "$runfiles_lib_path"
+  [ "$(rlocation r/f)" = "$tmpdir/f" ] || fail "expected a lookup through out=1.manifest, got: $(rlocation r/f)"
+
+  {
+    echo '#!/bin/sh'
+    sed -n '/^# *# --- begin runfiles.sh initialization v4 ---/,/^# *# --- end runfiles.sh initialization v4 ---/p' \
+      "$runfiles_lib_path" | sed 's/^#       //'
+    echo 'rlocation r/f'
+  } > "$tmpdir/script.sh"
+  actual=$(sh "$tmpdir/script.sh")
+  [ "$actual" = "$tmpdir/f" ] || fail "expected the snippet to find the library through out=1.manifest, got: $actual"
+}
+
+main() {
+  manifest_file="${RUNFILES_MANIFEST_FILE:-}"
+  dir="${RUNFILES_DIR:-}"
+  runfiles_lib_path=$(find_runfiles_lib)
+
+  tests="
+    test_rlocation_call_requires_no_envvars
+    test_rlocation_argument_validation
+    test_rlocation_abs_path
+    test_init_manifest_based_runfiles
+    test_manifest_based_envvars
+    test_init_directory_based_runfiles
+    test_init_derives_runfiles_dir_from_legacy_location
+    test_directory_based_runfiles_with_repo_mapping_from_main
+    test_directory_based_runfiles_with_repo_mapping_from_other_repo
+    test_directory_based_runfiles_with_repo_mapping_from_extension_repo
+    test_manifest_based_runfiles_with_repo_mapping_from_main
+    test_manifest_based_runfiles_with_repo_mapping_from_other_repo
+    test_manifest_based_runfiles_with_repo_mapping_from_extension_repo
+    test_directory_based_runfiles_with_repo_mapping_from_module_root_repo
+    test_directory_based_envvars
+    test_rlocation_auto_detects_source_repo_under_bash
+    test_runfiles_current_repository_under_set_u
+    test_current_repository_directory_based
+    test_current_repository_manifest_based
+    test_current_repository_directory_and_manifest_based
+    test_platform_detection_without_uname
+    test_manifest_prefix_respects_path_boundaries
+    test_manifest_lookup_case_insensitive
+    test_manifest_based_relative_symlink_targets
+    test_directory_based_relative_symlink_targets
+    test_awk_on_by_default
+    test_awk_disabled_by_env
+    test_awk_enabled_by_program
+    test_awk_falls_back_when_program_is_missing
+    test_survives_without_awk
+    test_init_snippet_aborts_when_library_fails
+    test_manifest_path_with_equals_sign
+  "
+  failure=0
+  for t in $tests; do
+    export RUNFILES_MANIFEST_FILE="$manifest_file"
+    export RUNFILES_DIR="$dir"
+    log_info "Running $t"
+    if ! ($t); then
+      log_fail "$t"
+      failure=1
+    fi
+  done
+  return $failure
+}
+
+main
diff --git a/tests/runfiles/runfiles_test_under_bash.sh b/tests/runfiles/runfiles_test_under_bash.sh
new file mode 100755
index 0000000..f3b0f23
--- /dev/null
+++ b/tests/runfiles/runfiles_test_under_bash.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# Copyright 2026 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Runs the POSIX suite under bash.
+#
+# runfiles_test.sh carries a `#!/bin/sh` shebang, so on Debian-based Linux it
+# runs under dash and exercises the library's portable code paths. Their bash
+# counterparts, BASH_SOURCE detection and `export -f`, are what most users get,
+# since the default sh_toolchain is bash on every platform.
+set -eu
+exec bash "$(dirname "$0")/runfiles_test.sh"