Repository: bazelbuild/bazel
Issue: Implement "Locating runfiles with Bzlmod" proposal
Labels: type: feature request
P2
team-ExternalDeps
area-Bzlmod

The ["Locating runfiles with Bzlmod" proposal](https://github.com/bazelbuild/proposals/blob/main/designs/2022-07-21-locating-runfiles-with-bzlmod.md) consists of the following individual steps:

* [x] ~Add the `RunfilesLibraryInfo` provider (#16125)~
* [x] Collect repository names and mappings of the transitive closure of a target (#16278)
* [x] Emit a repository mapping manifest for every executable (#16321 and https://github.com/bazelbuild/bazel/pull/16652)
* [x] Revert `RunfilesLibraryInfo`
* [x] Expose the current repository name in rules
  * [x] Bash (#16693)
  * [x] C++ (#16216)
  * [x] Java (#16534)
  * [x] Python (#16341)
* [x] Parse and use the repository mapping manifest in runfiles libraries (https://github.com/bazelbuild/bazel/issues/15029)
  * [x] Bash (#16693)
  * [x] C++ (#16623 and https://github.com/bazelbuild/bazel/pull/16701)
  * [x] Java (#16549)
  * [X] ~Python~ has been updated in rules_python
* [x] Use the Java runfiles library to make Stardoc work with repository mappings (https://github.com/bazelbuild/bazel/issues/14140)

Status of runfiles libraries in third-party rulesets:

* [x] rules_go (https://github.com/bazelbuild/rules_go/pull/3347)
* [ ] [rules_rust](https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs) (???)
* [ ] [rules_haskell](https://github.com/tweag/rules_haskell/blob/master/tools/runfiles/README.md) (???)

Issue comments:
@Wyverald Could you assign me and add the appropriate labels?
~~@comius Do you expect `java_binary` to be starlarkified in time for Bazel 6? That would simplify the changes to the Java rules.~~ Most likely no longer necessary, as the changes will apply to `buildjar` itself.
@Wyverald Oops, I missed the use of `Closes ...` in the PR description - we should use `Work towards ...` instead. Could you reopen? For some I lack the permission to do so.
It's the "To fix #NNN" line... GitHub trying to be clever here
The most likely future seems to be that we'll standardize on Python imports _not_ containing the repository name, in which case bzlmod is a no-op.

It's not an optimal solution because it requires an entry in `$PYTHONPATH` for each repository in the transitive closure of the Python binary, but it's the status quo and I'd much prefer thinking up a solution to that (e.g. binary-specific symlink trees that do not look like runfiles trees, dunno) than to standardize on having the repository names in imports because the concept of "repository" is specific to Bazel.

Put differently: the only way for bzlmod to cause trouble for Python is if we decide to require repository names in imports, which seems to be unlikely and it looks like the decision on that will take a while and I prefer not blocking either Bazel 6.0 or the removal of bzlmod from the experimental domain to avoid an unlikely failure mode. And should that happen, we can always paper over it with some sort of import hook.

/cc @rickeylev 
@oquenchil I'm thinking about whether we should use a macro to pass `BAZEL_CURRENT_REPOSITORY` to the `Rlocation` function automatically (e.g. do `#define Rlocation(path) RlocationReal(path, BAZEL_CURRENT_REPOSITORY)`). Do you think that would be too intrusive/magical?
Would users have to write that line or is it part of a file that is automatically generated?

I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.
> Would users have to write that line or is it part of a file that is automatically generated?
> 
> I don't mind adding whatever will make it easier but if it gets too magical it should maybe be wrapped so that the details aren't visible to the user unless they want to look.

@oquenchil I would want to make that magic part of the runfiles library header so that users don't have to write it themselves.

What I am worried about is having an `Rlocation` macro mess with people's existing codebase since there doesn't seem to be a way to put it in a namespace or restrict it to member functions only.
Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?
> Aren't we in control of the name of the macro? Can we rename it to something that would be very unlikely to clash with anything?

We can call it something else, we just won't be able to have existing C++ codebases use the new repo mapping-aware lookup automatically if we do so. But of course having to replace all `runfiles::create()` calls with something else won't be too bad.
If the macro name is Rlocation and that may start clashing with people's code in C++ files then I think it would be prudent to rename it if we decide to go with the macro.

I guess the call to make here is how much of a breaking change this is compared to the benefit of passing BAZEL_CURRENT_REPOSITORY automatically for users. I would say that the benefit is not too great but as far as I understood the use of Bazel runfiles in C++ code wasn't too wide-spread either?

>  But of course having to replace all runfiles::create() calls with something else won't be too bad.

How do you know? Is it based on search results from GH? If a release note would be enough for it not to be too disruptive then let's rename it.
I have experimented a bit more with APIs while working on the corresponding change for Java (https://github.com/bazelbuild/bazel/pull/16549).

What I now like more than the macro approach is to have users (optionally) pass in a canonical repository name when creating the `Runfiles` instance and default to that repo in `Rlocation` calls, while providing ways to override the default with an overload of `Rlocation` that accepts a repository name as a second parameter. In this way, users only have to pass in `BAZEL_CURRENT_REPOSITORY` only once in the common case, which should render a macro unnecessary.
Update: All changes relevant for Bazel 6.0.0 are now in review.
This is mostly done now, with only the bugfix https://github.com/bazelbuild/bazel/pull/16755 and a number of cherry-picks to 6.0.0 missing.
@Wyverald You can remove this from the "6.0.0 nice to have" milestone as the only remaining issue is not tied to a Bazel release (Stardoc).
Downgrading because the most important points have been addressed; the only outstanding issue is Stardoc, which is undergoing a rewrite currently by @tetromino.

Pull request review comments:

Patch that resolved the issue:
diff --git a/tools/cpp/runfiles/runfiles_src.cc b/tools/cpp/runfiles/runfiles_src.cc
index f35dd969949f4a..d81edb643f9cec 100644
--- a/tools/cpp/runfiles/runfiles_src.cc
+++ b/tools/cpp/runfiles/runfiles_src.cc
@@ -96,15 +96,13 @@ bool IsDirectory(const string& path) {
 
 bool PathsFrom(const std::string& argv0, std::string runfiles_manifest_file,
                std::string runfiles_dir, std::string* out_manifest,
-               std::string* out_directory, std::string* out_repo_mapping);
+               std::string* out_directory);
 
 bool PathsFrom(const std::string& argv0, std::string runfiles_manifest_file,
                std::string runfiles_dir,
                std::function<bool(const std::string&)> is_runfiles_manifest,
                std::function<bool(const std::string&)> is_runfiles_directory,
-               std::function<bool(const std::string&)> is_repo_mapping,
-               std::string* out_manifest, std::string* out_directory,
-               std::string* out_repo_mapping);
+               std::string* out_manifest, std::string* out_directory);
 
 bool ParseManifest(const string& path, map<string, string>* result,
                    string* error);
@@ -117,9 +115,9 @@ Runfiles* Runfiles::Create(const string& argv0,
                            const string& runfiles_manifest_file,
                            const string& runfiles_dir,
                            const string& source_repository, string* error) {
-  string manifest, directory, repo_mapping;
+  string manifest, directory;
   if (!PathsFrom(argv0, runfiles_manifest_file, runfiles_dir, &manifest,
-                 &directory, &repo_mapping)) {
+                 &directory)) {
     if (error) {
       std::ostringstream err;
       err << "ERROR: " << __FILE__ << "(" << __LINE__
@@ -144,10 +142,10 @@ Runfiles* Runfiles::Create(const string& argv0,
   }
 
   map<pair<string, string>, string> mapping;
-  if (!repo_mapping.empty()) {
-    if (!ParseRepoMapping(repo_mapping, &mapping, error)) {
-      return nullptr;
-    }
+  if (!ParseRepoMapping(
+          RlocationUnchecked("_repo_mapping", runfiles, directory), &mapping,
+          error)) {
+    return nullptr;
   }
 
   return new Runfiles(std::move(runfiles), std::move(directory),
@@ -196,28 +194,28 @@ string Runfiles::Rlocation(const string& path,
     return path;
   }
 
-  if (repo_mapping_.empty()) {
-    return RlocationUnchecked(path);
-  }
   string::size_type first_slash = path.find_first_of('/');
   if (first_slash == string::npos) {
-    return RlocationUnchecked(path);
+    return RlocationUnchecked(path, runfiles_map_, directory_);
   }
   string target_apparent = path.substr(0, first_slash);
   auto target =
       repo_mapping_.find(std::make_pair(source_repo, target_apparent));
   if (target == repo_mapping_.cend()) {
-    return RlocationUnchecked(path);
+    return RlocationUnchecked(path, runfiles_map_, directory_);
   }
-  return RlocationUnchecked(target->second + path.substr(first_slash));
+  return RlocationUnchecked(target->second + path.substr(first_slash),
+                            runfiles_map_, directory_);
 }
 
-string Runfiles::RlocationUnchecked(const string& path) const {
-  const auto exact_match = runfiles_map_.find(path);
-  if (exact_match != runfiles_map_.end()) {
+string Runfiles::RlocationUnchecked(const string& path,
+                                    const map<string, string>& runfiles_map,
+                                    const string& directory) {
+  const auto exact_match = runfiles_map.find(path);
+  if (exact_match != runfiles_map.end()) {
     return exact_match->second;
   }
-  if (!runfiles_map_.empty()) {
+  if (!runfiles_map.empty()) {
     // 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
@@ -226,14 +224,14 @@ string Runfiles::RlocationUnchecked(const string& path) const {
     while ((prefix_end = path.find_last_of('/', prefix_end - 1)) !=
            string::npos) {
       const string prefix = path.substr(0, prefix_end);
-      const auto prefix_match = runfiles_map_.find(prefix);
-      if (prefix_match != runfiles_map_.end()) {
+      const auto prefix_match = runfiles_map.find(prefix);
+      if (prefix_match != runfiles_map.end()) {
         return prefix_match->second + "/" + path.substr(prefix_end + 1);
       }
     }
   }
-  if (!directory_.empty()) {
-    return directory_ + "/" + path;
+  if (!directory.empty()) {
+    return directory + "/" + path;
   }
   return "";
 }
@@ -279,13 +277,7 @@ bool ParseRepoMapping(const string& path,
                       string* error) {
   std::ifstream stm(path);
   if (!stm.is_open()) {
-    if (error) {
-      std::ostringstream err;
-      err << "ERROR: " << __FILE__ << "(" << __LINE__
-          << "): cannot open repository mapping \"" << path << "\"";
-      *error = err.str();
-    }
-    return false;
+    return true;
   }
   string line;
   std::getline(stm, line);
@@ -333,12 +325,9 @@ namespace testing {
 bool TestOnly_PathsFrom(const string& argv0, string mf, string dir,
                         function<bool(const string&)> is_runfiles_manifest,
                         function<bool(const string&)> is_runfiles_directory,
-                        function<bool(const string&)> is_repo_mapping,
-                        string* out_manifest, string* out_directory,
-                        string* out_repo_mapping) {
+                        string* out_manifest, string* out_directory) {
   return PathsFrom(argv0, mf, dir, is_runfiles_manifest, is_runfiles_directory,
-                   is_repo_mapping, out_manifest, out_directory,
-                   out_repo_mapping);
+                   out_manifest, out_directory);
 }
 
 bool TestOnly_IsAbsolute(const string& path) { return IsAbsolute(path); }
@@ -376,23 +365,19 @@ Runfiles* Runfiles::CreateForTest(std::string* error) {
 namespace {
 
 bool PathsFrom(const string& argv0, string mf, string dir, string* out_manifest,
-               string* out_directory, string* out_repo_mapping) {
+               string* out_directory) {
   return PathsFrom(
       argv0, mf, dir, [](const string& path) { return IsReadableFile(path); },
-      [](const string& path) { return IsDirectory(path); },
-      [](const string& path) { return IsReadableFile(path); }, out_manifest,
-      out_directory, out_repo_mapping);
+      [](const string& path) { return IsDirectory(path); }, out_manifest,
+      out_directory);
 }
 
 bool PathsFrom(const string& argv0, string mf, string dir,
                function<bool(const string&)> is_runfiles_manifest,
                function<bool(const string&)> is_runfiles_directory,
-               function<bool(const string&)> is_repo_mapping,
-               string* out_manifest, string* out_directory,
-               string* out_repo_mapping) {
+               string* out_manifest, string* out_directory) {
   out_manifest->clear();
   out_directory->clear();
-  out_repo_mapping->clear();
 
   bool mfValid = is_runfiles_manifest(mf);
   bool dirValid = is_runfiles_directory(dir);
@@ -428,21 +413,6 @@ bool PathsFrom(const string& argv0, string mf, string dir,
     dirValid = is_runfiles_directory(dir);
   }
 
-  string rm;
-  bool rmValid = false;
-
-  if (dirValid && ends_with(dir, ".runfiles")) {
-    rm = dir.substr(0, dir.size() - 9) + ".repo_mapping";
-    rmValid = is_repo_mapping(rm);
-  }
-
-  if (!rmValid && mfValid &&
-      (ends_with(mf, ".runfiles_manifest") ||
-       ends_with(mf, ".runfiles/MANIFEST"))) {
-    rm = mf.substr(0, mf.size() - 18) + ".repo_mapping";
-    rmValid = is_repo_mapping(rm);
-  }
-
   if (mfValid) {
     *out_manifest = mf;
   }
@@ -451,10 +421,6 @@ bool PathsFrom(const string& argv0, string mf, string dir,
     *out_directory = dir;
   }
 
-  if (rmValid) {
-    *out_repo_mapping = rm;
-  }
-
   return true;
 }
 
diff --git a/tools/cpp/runfiles/runfiles_src.h b/tools/cpp/runfiles/runfiles_src.h
index 6e0a0c2f203556..75103e230bf8ce 100644
--- a/tools/cpp/runfiles/runfiles_src.h
+++ b/tools/cpp/runfiles/runfiles_src.h
@@ -206,14 +206,17 @@ class Runfiles {
   Runfiles& operator=(const Runfiles&) = delete;
   Runfiles& operator=(Runfiles&&) = delete;
 
+  static std::string RlocationUnchecked(
+      const std::string& path,
+      const std::map<std::string, std::string>& runfiles_map,
+      const std::string& directory);
+
   const std::map<std::string, std::string> runfiles_map_;
   const std::string directory_;
   const std::map<std::pair<std::string, std::string>, std::string>
       repo_mapping_;
   const std::vector<std::pair<std::string, std::string> > envvars_;
   const std::string source_repository_;
-
-  std::string RlocationUnchecked(const std::string& path) const;
 };
 
 // The "testing" namespace contains functions that allow unit testing the code.
@@ -243,9 +246,7 @@ bool TestOnly_PathsFrom(
     std::string runfiles_dir,
     std::function<bool(const std::string&)> is_runfiles_manifest,
     std::function<bool(const std::string&)> is_runfiles_directory,
-    std::function<bool(const std::string&)> is_repo_mapping,
-    std::string* out_manifest, std::string* out_directory,
-    std::string* out_repo_mapping);
+    std::string* out_manifest, std::string* out_directory);
 
 // For testing only.
 // Returns true if `path` is an absolute Unix or Windows path.
diff --git a/tools/cpp/runfiles/runfiles_test.cc b/tools/cpp/runfiles/runfiles_test.cc
index 771510112ad28d..b859968f33dad1 100644
--- a/tools/cpp/runfiles/runfiles_test.cc
+++ b/tools/cpp/runfiles/runfiles_test.cc
@@ -494,135 +494,106 @@ TEST_F(RunfilesTest, PathsFromEnvVars) {
   EXPECT_TRUE(TestOnly_PathsFrom(
       "argv0", "mock1.runfiles/MANIFEST", "mock2.runfiles",
       [](const string& path) { return path == "mock1.runfiles/MANIFEST"; },
-      [](const string& path) { return path == "mock2.runfiles"; },
-      [](const string& path) { return path == "mock2.repo_mapping"; }, &mf,
-      &dir, &rm));
+      [](const string& path) { return path == "mock2.runfiles"; }, &mf, &dir));
   EXPECT_EQ(mf, "mock1.runfiles/MANIFEST");
   EXPECT_EQ(dir, "mock2.runfiles");
-  EXPECT_EQ(rm, "mock2.repo_mapping");
 
   // RUNFILES_MANIFEST_FILE is invalid but RUNFILES_DIR is good and there's a
   // runfiles manifest in the runfiles directory.
   EXPECT_TRUE(TestOnly_PathsFrom(
       "argv0", "mock1.runfiles/MANIFEST", "mock2.runfiles",
       [](const string& path) { return path == "mock2.runfiles/MANIFEST"; },
-      [](const string& path) { return path == "mock2.runfiles"; },
-      [](const string& path) { return path == "mock2.repo_mapping"; }, &mf,
-      &dir, &rm));
+      [](const string& path) { return path == "mock2.runfiles"; }, &mf, &dir));
   EXPECT_EQ(mf, "mock2.runfiles/MANIFEST");
   EXPECT_EQ(dir, "mock2.runfiles");
-  EXPECT_EQ(rm, "mock2.repo_mapping");
 
   // RUNFILES_MANIFEST_FILE is invalid but RUNFILES_DIR is good, but there's no
   // runfiles manifest in the runfiles directory.
   EXPECT_TRUE(TestOnly_PathsFrom(
       "argv0", "mock1.runfiles/MANIFEST", "mock2.runfiles",
       [](const string& path) { return false; },
-      [](const string& path) { return path == "mock2.runfiles"; },
-      [](const string& path) { return path == "mock2.repo_mapping"; }, &mf,
-      &dir, &rm));
+      [](const string& path) { return path == "mock2.runfiles"; }, &mf, &dir));
   EXPECT_EQ(mf, "");
   EXPECT_EQ(dir, "mock2.runfiles");
-  EXPECT_EQ(rm, "mock2.repo_mapping");
 
   // RUNFILES_DIR is invalid but RUNFILES_MANIFEST_FILE is good, and it is in
   // a valid-looking runfiles directory.
   EXPECT_TRUE(TestOnly_PathsFrom(
       "argv0", "mock1.runfiles/MANIFEST", "mock2",
       [](const string& path) { return path == "mock1.runfiles/MANIFEST"; },
-      [](const string& path) { return path == "mock1.runfiles"; },
-      [](const string& path) { return path == "mock1.repo_mapping"; }, &mf,
-      &dir, &rm));
+      [](const string& path) { return path == "mock1.runfiles"; }, &mf, &dir));
   EXPECT_EQ(mf, "mock1.runfiles/MANIFEST");
   EXPECT_EQ(dir, "mock1.runfiles");
-  EXPECT_EQ(rm, "mock1.repo_mapping");
 
   // RUNFILES_DIR is invalid but RUNFILES_MANIFEST_FILE is good, but it is not
   // in any valid-looking runfiles directory.
   EXPECT_TRUE(TestOnly_PathsFrom(
       "argv0", "mock1/MANIFEST", "mock2",
       [](const string& path) { return path == "mock1/MANIFEST"; },
-      [](const string& path) { return false; },
-      [](const string& path) { return true; }, &mf, &dir, &rm));
+      [](const string& path) { return false; }, &mf, &dir));
   EXPECT_EQ(mf, "mock1/MANIFEST");
   EXPECT_EQ(dir, "");
-  EXPECT_EQ(rm, "");
 
   // Both envvars are invalid, but there's a manifest in a runfiles directory
   // next to argv0, however there's no other content in the runfiles directory.
   EXPECT_TRUE(TestOnly_PathsFrom(
       "argv0", "mock1/MANIFEST", "mock2",
       [](const string& path) { return path == "argv0.runfiles/MANIFEST"; },
-      [](const string& path) { return false; },
-      [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
-      &dir, &rm));
+      [](const string& path) { return false; }, &mf, &dir));
   EXPECT_EQ(mf, "argv0.runfiles/MANIFEST");
   EXPECT_EQ(dir, "");
-  EXPECT_EQ(rm, "argv0.repo_mapping");
 
   // Both envvars are invalid, but there's a manifest next to argv0. There's
   // no runfiles tree anywhere.
   EXPECT_TRUE(TestOnly_PathsFrom(
       "argv0", "mock1/MANIFEST", "mock2",
       [](const string& path) { return path == "argv0.runfiles_manifest"; },
-      [](const string& path) { return false; },
-      [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
-      &dir, &rm));
+      [](const string& path) { return false; }, &mf, &dir));
   EXPECT_EQ(mf, "argv0.runfiles_manifest");
   EXPECT_EQ(dir, "");
-  EXPECT_EQ(rm, "argv0.repo_mapping");
 
   // Both envvars are invalid, but there's a valid manifest next to argv0, and a
   // valid runfiles directory (without a manifest in it).
   EXPECT_TRUE(TestOnly_PathsFrom(
       "argv0", "mock1/MANIFEST", "mock2",
       [](const string& path) { return path == "argv0.runfiles_manifest"; },
-      [](const string& path) { return path == "argv0.runfiles"; },
-      [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
-      &dir, &rm));
+      [](const string& path) { return path == "argv0.runfiles"; }, &mf, &dir));
   EXPECT_EQ(mf, "argv0.runfiles_manifest");
   EXPECT_EQ(dir, "argv0.runfiles");
-  EXPECT_EQ(rm, "argv0.repo_mapping");
 
   // Both envvars are invalid, but there's a valid runfiles directory next to
   // argv0, though no manifest in it.
   EXPECT_TRUE(TestOnly_PathsFrom(
       "argv0", "mock1/MANIFEST", "mock2",
       [](const string& path) { return false; },
-      [](const string& path) { return path == "argv0.runfiles"; },
-      [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
-      &dir, &rm));
+      [](const string& path) { return path == "argv0.runfiles"; }, &mf, &dir));
   EXPECT_EQ(mf, "");
   EXPECT_EQ(dir, "argv0.runfiles");
-  EXPECT_EQ(rm, "argv0.repo_mapping");
 
   // Both envvars are invalid, but there's a valid runfiles directory next to
   // argv0 with a valid manifest in it.
   EXPECT_TRUE(TestOnly_PathsFrom(
       "argv0", "mock1/MANIFEST", "mock2",
       [](const string& path) { return path == "argv0.runfiles/MANIFEST"; },
-      [](const string& path) { return path == "argv0.runfiles"; },
-      [](const string& path) { return path == "argv0.repo_mapping"; }, &mf,
-      &dir, &rm));
+      [](const string& path) { return path == "argv0.runfiles"; }, &mf, &dir));
   EXPECT_EQ(mf, "argv0.runfiles/MANIFEST");
   EXPECT_EQ(dir, "argv0.runfiles");
-  EXPECT_EQ(rm, "argv0.repo_mapping");
 }
 
 TEST_F(RunfilesTest, ManifestBasedRlocationWithRepoMapping_fromMain) {
   string uid = LINE_AS_STRING();
+  unique_ptr<MockFile> rm(MockFile::Create(
+      "foo" + uid + ".repo_mapping",
+      {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
+       ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
+  ASSERT_TRUE(rm != nullptr);
   unique_ptr<MockFile> mf(MockFile::Create(
       "foo" + uid + ".runfiles_manifest",
-      {"config.json /etc/config.json",
+      {"_repo_mapping " + rm->Path(), "config.json /etc/config.json",
        "protobuf~3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile",
        "_main/bar/runfile /the/path/./to/other//other runfile.txt",
        "protobuf~3.19.2/bar/dir E:\\Actual Path\\Directory"}));
-  EXPECT_TRUE(mf != nullptr);
-  unique_ptr<MockFile> rm(MockFile::Create(
-      "foo" + uid + ".repo_mapping",
-      {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
-       ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
-  EXPECT_TRUE(rm != nullptr);
+  ASSERT_TRUE(mf != nullptr);
   string argv0(mf->Path().substr(
       0, mf->Path().size() - string(".runfiles_manifest").size()));
 
@@ -667,18 +638,18 @@ TEST_F(RunfilesTest, ManifestBasedRlocationWithRepoMapping_fromMain) {
 
 TEST_F(RunfilesTest, ManifestBasedRlocationWithRepoMapping_fromOtherRepo) {
   string uid = LINE_AS_STRING();
+  unique_ptr<MockFile> rm(MockFile::Create(
+      "foo" + uid + ".repo_mapping",
+      {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
+       ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
+  ASSERT_TRUE(rm != nullptr);
   unique_ptr<MockFile> mf(MockFile::Create(
       "foo" + uid + ".runfiles_manifest",
-      {"config.json /etc/config.json",
+      {"_repo_mapping " + rm->Path(), "config.json /etc/config.json",
        "protobuf~3.19.2/foo/runfile C:/Actual Path\\protobuf\\runfile",
        "_main/bar/runfile /the/path/./to/other//other runfile.txt",
        "protobuf~3.19.2/bar/dir E:\\Actual Path\\Directory"}));
-  EXPECT_TRUE(mf != nullptr);
-  unique_ptr<MockFile> rm(MockFile::Create(
-      "foo" + uid + ".repo_mapping",
-      {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
-       ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
-  EXPECT_TRUE(rm != nullptr);
+  ASSERT_TRUE(mf != nullptr);
   string argv0(mf->Path().substr(
       0, mf->Path().size() - string(".runfiles_manifest").size()));
 
@@ -721,17 +692,13 @@ TEST_F(RunfilesTest, ManifestBasedRlocationWithRepoMapping_fromOtherRepo) {
 
 TEST_F(RunfilesTest, DirectoryBasedRlocationWithRepoMapping_fromMain) {
   string uid = LINE_AS_STRING();
-  unique_ptr<MockFile> dir_marker(
-      MockFile::Create("foo" + uid + ".runfiles/marker"), {});
-  EXPECT_TRUE(dir_marker != nullptr);
-  string dir = dir_marker->DirName();
   unique_ptr<MockFile> rm(MockFile::Create(
-      "foo" + uid + ".repo_mapping",
+      "foo" + uid + ".runfiles/_repo_mapping",
       {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
        ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
-  EXPECT_TRUE(rm != nullptr);
-  string argv0(
-      rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+  ASSERT_TRUE(rm != nullptr);
+  string dir = rm->DirName();
+  string argv0(dir.substr(0, dir.size() - string(".runfiles").size()));
 
   string error;
   unique_ptr<Runfiles> r(Runfiles::Create(argv0, "", "", "", &error));
@@ -770,17 +737,13 @@ TEST_F(RunfilesTest, DirectoryBasedRlocationWithRepoMapping_fromMain) {
 
 TEST_F(RunfilesTest, DirectoryBasedRlocationWithRepoMapping_fromOtherRepo) {
   string uid = LINE_AS_STRING();
-  unique_ptr<MockFile> dir_marker(
-      MockFile::Create("foo" + uid + ".runfiles/marker"), {});
-  EXPECT_TRUE(dir_marker != nullptr);
-  string dir = dir_marker->DirName();
   unique_ptr<MockFile> rm(MockFile::Create(
-      "foo" + uid + ".repo_mapping",
+      "foo" + uid + ".runfiles/_repo_mapping",
       {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
        ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
-  EXPECT_TRUE(rm != nullptr);
-  string argv0(
-      rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+  ASSERT_TRUE(rm != nullptr);
+  string dir = rm->DirName();
+  string argv0(dir.substr(0, dir.size() - string(".runfiles").size()));
 
   string error;
   unique_ptr<Runfiles> r(
@@ -817,17 +780,13 @@ TEST_F(RunfilesTest, DirectoryBasedRlocationWithRepoMapping_fromOtherRepo) {
 TEST_F(RunfilesTest,
        DirectoryBasedRlocationWithRepoMapping_fromOtherRepo_withSourceRepo) {
   string uid = LINE_AS_STRING();
-  unique_ptr<MockFile> dir_marker(
-      MockFile::Create("foo" + uid + ".runfiles/marker"), {});
-  EXPECT_TRUE(dir_marker != nullptr);
-  string dir = dir_marker->DirName();
   unique_ptr<MockFile> rm(MockFile::Create(
-      "foo" + uid + ".repo_mapping",
+      "foo" + uid + ".runfiles/_repo_mapping",
       {",my_module,_main", ",my_protobuf,protobuf~3.19.2",
        ",my_workspace,_main", "protobuf~3.19.2,protobuf,protobuf~3.19.2"}));
-  EXPECT_TRUE(rm != nullptr);
-  string argv0(
-      rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+  ASSERT_TRUE(rm != nullptr);
+  string dir = rm->DirName();
+  string argv0(dir.substr(0, dir.size() - string(".runfiles").size()));
 
   string error;
   unique_ptr<Runfiles> r(Runfiles::Create(argv0, "", "", "", &error));
@@ -863,15 +822,11 @@ TEST_F(RunfilesTest,
 
 TEST_F(RunfilesTest, InvalidRepoMapping) {
   string uid = LINE_AS_STRING();
-  unique_ptr<MockFile> dir_marker(
-      MockFile::Create("foo" + uid + ".runfiles/marker"), {});
-  EXPECT_TRUE(dir_marker != nullptr);
-  string dir = dir_marker->DirName();
   unique_ptr<MockFile> rm(
-      MockFile::Create("foo" + uid + ".repo_mapping", {"a,b"}));
-  EXPECT_TRUE(rm != nullptr);
-  string argv0(
-      rm->Path().substr(0, rm->Path().size() - string(".repo_mapping").size()));
+      MockFile::Create("foo" + uid + ".runfiles/_repo_mapping", {"a,b"}));
+  ASSERT_TRUE(rm != nullptr);
+  string dir = rm->DirName();
+  string argv0(dir.substr(0, dir.size() - string(".runfiles").size()));
 
   string error;
   unique_ptr<Runfiles> r(Runfiles::Create(argv0, "", "", "", &error));


Test patch:
diff --git a/src/test/py/bazel/bzlmod/bazel_module_test.py b/src/test/py/bazel/bzlmod/bazel_module_test.py
index b9fd78688c8d49..5da5f7802962f1 100644
--- a/src/test/py/bazel/bzlmod/bazel_module_test.py
+++ b/src/test/py/bazel/bzlmod/bazel_module_test.py
@@ -762,5 +762,57 @@ def testJavaRunfilesLibraryRepoMapping(self):
         env_add={'RUNFILES_LIB_DEBUG': '1'})
     self.AssertExitCode(exit_code, 0, stderr, stdout)
 
+  def testCppRunfilesLibraryRepoMapping(self):
+    self.main_registry.setModuleBasePath('projects')
+    projects_dir = self.main_registry.projects
+
+    self.main_registry.createLocalPathModule('data', '1.0', 'data')
+    projects_dir.joinpath('data').mkdir(exist_ok=True)
+    scratchFile(projects_dir.joinpath('data', 'WORKSPACE'))
+    scratchFile(projects_dir.joinpath('data', 'foo.txt'), ['hello'])
+    scratchFile(
+        projects_dir.joinpath('data', 'BUILD'), ['exports_files(["foo.txt"])'])
+
+    self.main_registry.createLocalPathModule('test', '1.0', 'test',
+                                             {'data': '1.0'})
+    projects_dir.joinpath('test').mkdir(exist_ok=True)
+    scratchFile(projects_dir.joinpath('test', 'WORKSPACE'))
+    scratchFile(
+        projects_dir.joinpath('test', 'BUILD'), [
+          'cc_test(',
+          '    name = "test",',
+          '    srcs = ["test.cpp"],',
+          '    data = ["@data//:foo.txt"],',
+          '    args = ["$(rlocationpath @data//:foo.txt)"],',
+          '    deps = ["@bazel_tools//tools/cpp/runfiles"],',
+          ')',
+        ])
+    scratchFile(
+        projects_dir.joinpath('test', 'test.cpp'), [
+          '#include <cstdlib>',
+          '#include <fstream>',
+          '#include "tools/cpp/runfiles/runfiles.h"',
+          'using bazel::tools::cpp::runfiles::Runfiles;',
+          'int main(int argc, char** argv) {',
+          '  Runfiles* runfiles = Runfiles::Create(argv[0], BAZEL_CURRENT_REPOSITORY);',
+          '  std::ifstream f1(runfiles->Rlocation(argv[1]));',
+          '  if (!f1.good()) std::exit(1);',
+          '  std::ifstream f2(runfiles->Rlocation("data/foo.txt"));',
+          '  if (!f2.good()) std::exit(2);',
+          '}',
+        ])
+
+    self.ScratchFile('MODULE.bazel', ['bazel_dep(name="test",version="1.0")'])
+    self.ScratchFile('WORKSPACE')
+
+    # Run sandboxed on Linux and macOS.
+    exit_code, stderr, stdout = self.RunBazel(
+        ['test', '@test//:test', '--test_output=errors'], allow_failure=True)
+    self.AssertExitCode(exit_code, 0, stderr, stdout)
+    # Run unsandboxed on all platforms.
+    exit_code, stderr, stdout = self.RunBazel(['run', '@test//:test'],
+                                              allow_failure=True)
+    self.AssertExitCode(exit_code, 0, stderr, stdout)
+
 if __name__ == '__main__':
   unittest.main()